用字典替换字符串中的多个单词(python)

时间:2016-05-08 18:04:55

标签: python dictionary replace

我希望用户输入一个词组,并且当" happy" /" sad"在短语内,我希望程序返回这些单词替换它们在字典中的值。这是我的代码:

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

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

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)