我如何比较两个单词列表,更改共同的单词,并在python中打印结果?

时间:2013-02-15 17:22:40

标签: python python-3.x

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

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

所以我试图得到它以便小写单词的共同点,保留在新句子中,没有原文,并且没有它们变成标题的情况。

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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"