【问题标题】:Match words in lists and replace that word in the second list with its pair in the first list匹配列表中的单词并将第二个列表中的单词替换为第一个列表中的对
【发布时间】:2015-05-12 07:53:21
【问题描述】:

我有一个包含单词对的列表。它看起来像这样:

words = ["I : You", "Me : You", "Mine : Yours"]

通过输入和拆分,我根据用户键入的句子创建了一个新列表。

我想做的是检查这个新列表(我们称之为句子)是否包含列表“单词”所做的任何单词。如果是这样,我希望它用“单词”列表中的对替换该单词,然后用替换的单词打印句子。

例如: 程序问:“你好吗?” 用户回答:“我很好” 程序回答:“你很好”

关于如何做到这一点的任何建议?

【问题讨论】:

  • 看起来像字典,而不是列表
  • 如果不是字典,应该是

标签: python list replace match


【解决方案1】:

我相信这就是您正在寻找的:

words = {"I" : "You", "Me" : "You", "Mine" : "Yours"}

sentence = "I am John Doe."

for word, replacement in words.items(): # works through the word pairs
    sentence.replace(word, replacement) # replacing with the counterpart

这句话现在是You are John Doe.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多