如何比较两个单词列表,更改常用单词,并用python打印结果?

如何比较两个单词列表,更改常用单词,并用python打印结果?,python,python-3.x,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

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

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

因此,我试图使小写的常用词保留在新句子中,而不保留原文,也不将它们改为标题大小写。

如果您想做的只是查看
lst
的任何元素是否出现在
common
中,您可以这样做

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

如果您要做的只是查看
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"

我认为您需要澄清这一点-如果
common=
,预期的输出是什么。。。0)现在,1)
[]
,2)
['is']
,以及3)
=lst
,很抱歉不清楚。基本上是尝试创建一个标题,其中常用词保持小写。常用词在单独的列表中,标题是传递到我的函数中的任何字符串。尽管我已经把常用词分离出来,并用标题字符串重印了一遍,但我还是被困在了如何修改句子的问题上,而不必对找到的常用词进行重复。(顺便说一句,我也忘了把“是”放在原来的常用列表中,oops)感谢大家的帮助。我想你需要澄清一下这一点-如果
common=
,预期的输出是什么。。。0)现在,1)
[]
,2)
['is']
,以及3)
=lst
,很抱歉不清楚。基本上是尝试创建一个标题,其中常用词保持小写。常用词在单独的列表中,标题是传递到我的函数中的任何字符串。尽管我已经把常用词分离出来,并用标题字符串重印了一遍,但我还是被困在了如何修改句子的问题上,而不必对找到的常用词进行重复。(顺便说一句,我也忘了把“是”放在原来的常用列表中,哦)谢谢大家的帮助。谢谢。这很有效,对我的作业很有帮助。@GP89否,对整个字符串调用
capitalize()
,除第一个字母外,其他字母都将小写。谢谢。这很有效,对我的作业也很有帮助。@GP89否,对整个字符串调用
capitalize()
,除第一个字母外,其他字母都将小写。谢谢两种解释。@Malvek没问题。另一方面,如果你关于堆栈溢出的问题与家庭作业有关,最好提前说明,这样人们就可以帮助你理解问题,而不仅仅是帮你做工作:-)谢谢两种解释。@Malvek没问题。另一方面,如果你关于堆栈溢出的问题与家庭作业有关,最好提前说明,这样人们会帮助你理解问题,而不仅仅是帮你做作业:-)