[英]How can i compare two lists of words, change the words that are in common, and print the result in python?
if i have a list of strings- 如果我有一个字符串列表,
common = ['the','in','a','for','is']
and i have a sentence broken up into a list- 我有一句话被分解成一个列表
lst = ['the', 'man', 'is', 'in', 'the', 'barrel']
how can i compare the two,and if there are any words in common, then print the full string again as a title. 我该如何比较两者,如果有共同的词,然后再次打印完整的字符串作为标题。 I have part of it working but my end result prints out the newly changed in common strings as well as the original. 我有一部分工作了,但是我的最终结果将打印出新更改的通用字符串以及原始字符串。
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)
output: 输出:
The Man is Is in In the The Barrel
so I'm trying to get it so that the lower case words in common, stay in the new sentence, without the originals, and without them changing into title case. 因此,我试图使它成为普通的小写单词,保留在新句子中,而没有原始词,也没有将它们变为标题大小写。
>>> 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'
If all you're trying to do is to see whether any of the elements of lst
appear in common
, you can do 如果您要做的只是查看lst
任何元素是否出现common
,则可以执行
>>> common = ['the','in','a','for']
>>> lst = ['the', 'man', 'is', 'in', 'the', 'barrel']
>>> list(set(common).intersection(lst))
['the', 'in']
and just check to see whether the resulting list has any elements in it. 然后检查结果列表中是否包含任何元素。
If you want the words in common
to be lowercased and you want all of the other words to be uppercased, do something like this: 如果要使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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.