0

如果我有一个字符串列表-

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

我有一个句子被分解成一个列表-

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

我如何比较两者,如果有任何共同的单词,然后再次打印完整的字符串作为标题。我有一部分工作,但我的最终结果打印出新更改的公共字符串以及原始字符串。

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']

并检查结果列表中是否包含任何元素。

如果您希望单词 incommon小写并且您希望所有其他单词大写,请执行以下操作:

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 回答