【问题标题】:Replace multiple words in string with dictionary (python)用字典替换字符串中的多个单词(python)
【发布时间】:2016-05-09 02:16:23
【问题描述】:

我希望用户输入一个短语,当短语中包含“快乐”/“悲伤”这两个词时,我希望程序返回这些词替换为它们在字典中的值。这是我的代码:

# dictionary
thesaurus = {
              "happy": "glad",
              "sad"  : "bleak"
            }

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)

# testing input
counter = 0
for x in part2:
    if part2[counter] in thesaurus.keys():
        phrase.replace(part2[counter], thesaurus.values()) # replace with dictionary value???
        print (phrase)
    counter += 1

代码有效,但我似乎无法弄清楚如何替换多个单词以让程序打印替换的单词。

所以如果用户输入

"Hello I am sad" 

想要的输出是

"Hello I am bleak"

任何帮助将不胜感激!

【问题讨论】:

  • 理想的输出效果如何?需要阳性对照/测试
  • 您要解决的具体问题是什么?用同义词替换短语中的一些单词?
  • 拆分的时候已经返回了一个列表,所以不需要强制转换为列表。
  • @aaaaaa 编辑了上面的原帖

标签: python dictionary replace


【解决方案1】:

翻译输入句子中的所有单词,然后加入翻译部分:

translated = []
for x in part2:
    t = thesaurus.get(x, x)  # replaces if found in thesaurus, else keep as it is
    translated.append(t)

newphrase = ' '.join(translated)

【讨论】:

  • 谢谢!如果我希望字典中的新单词以大写形式打印,我应该在哪里添加“.upper()”?
  • 如果只有在找到这个词时,我会使用类似t = thesaurus[x].upper() if thesaurus.get(x) else x
  • 谢谢!如果我要更改代码以包含更多与字典键关联的单词,例如 "sad" :["bleak", "blue", "depressed"] ,我将如何更改上述答案以返回字典中列表中的随机单词?我正在尝试包含 popitem() 但似乎无法将其放置在代码中的正确位置
  • 使用 pop() 将从字典中删除项目,所以这不是一个好主意。其次,如果你想要一个随机元素,要么生成一个随机索引以从列表中获取一个元素,要么使用一个集合并从中提取。这个答案可能很有用:stackoverflow.com/questions/59825/…。因此,在我的示例中,如果在字典中找到 x,则从 set(t) 绘制。
猜你喜欢
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2022-11-10
  • 1970-01-01
  • 2014-04-01
  • 2013-12-28
  • 1970-01-01
相关资源
最近更新 更多