0

文字列のリストがある場合-

common = ['the','in','a','for','is']

そして私はリストに分割された文を持っています-

lst = ['the', 'man', 'is', 'in', 'the', 'barrel']

2つを比較するにはどうすればよいですか。共通の単語がある場合は、文字列全体をタイトルとして再度印刷します。一部は機能していますが、最終結果では、元の文字列だけでなく、新しく変更された共通の文字列も出力されます。

new_title = lst.pop(0).title()
for word in lst:
    for word2 in common:
        if word == word2:
            new_title = new_title + ' ' + word

    new_title = new_title + ' ' + word.title()

print(new_title)

出力:

The Man is Is in In the The Barrel

だから私は、小文字の単語が共通して、元の単語がなく、タイトルの大文字小文字に変更されることなく、新しい文にとどまるようにしようとしています。

4

2 に答える 2

4
>>> new_title = ' '.join(w.title() if w not in common else w for w in lst)
>>> new_title = new_title[0].capitalize() + new_title[1:]
'The Man Is in the Barrel'
于 2013-02-15T17:34:39.567 に答える
0

の要素のいずれかが に表示lstされるかどうかを確認するだけのcommon場合は、次のことができます。

>>> common = ['the','in','a','for']
>>> lst = ['the', 'man', 'is', 'in', 'the', 'barrel']
>>> list(set(common).intersection(lst))
['the', 'in']

結果のリストに要素が含まれているかどうかを確認するだけです。

の単語をcommon小文字にし、他のすべての単語を大文字にしたい場合は、次のようにします。

def title_case(words):
    common = {'the','in','a','for'}
    partial = ' '.join(word.title() if word not in common else word for word in words)
    return partial[0].capitalize() + partial[1:]

words = ['the', 'man', 'is', 'in', 'the', 'barrel']
title_case(words) # gives "The Man Is in the Barrel"
于 2013-02-15T17:35:54.633 に答える