【问题标题】:How can i compare two lists of words, change the words that are in common, and print the result in python?我如何比较两个单词列表,更改共同的单词,并在 python 中打印结果?
【发布时间】:2013-02-15 17:22:40
【问题描述】:

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

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

所以我试图得到它,以便共同的小写单词留在新句子中,没有原件,也没有它们变成标题大小写。

【问题讨论】:

  • 我认为您需要澄清这一点 - 如果common = ... 0) 像现在这样,1) [],2) ['is'] 和 3),预期的输出是什么= lst
  • 抱歉不清楚。基本上试图创建一个标题,其中常用词以小写形式保存。常用词在单独的列表中,标题是传递给我的函数的任何字符串。虽然我已经完成了分离常用词的工作,并用标题字符串重新打印它,但我仍然坚持如何修改我的句子,而不用加倍找到常用词。 (ps 我也忘了把'is'放在原来的常用列表中,哎呀)谢谢大家的帮助。

标签: python python-3.x


【解决方案1】:
>>> 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'

【讨论】:

  • 谢谢。这很有效,对我的任务很有帮助。
  • @GP89 ​​不,在整个字符串上调用 capitalize() 会将除第一个之外的每个字母都小写。
【解决方案2】:

如果您只想查看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"

【讨论】:

  • 感谢您的解释。
  • @Malvek 没问题。附带说明一下,如果您在 Stack Overflow 上的问题与家庭作业有关,最好提前说明,这样人们会帮助您理解问题,而不仅仅是为您完成工作:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2016-12-19
  • 2015-04-08
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多