问题描述
我正在尝试创建一个程序,用字典中与之对应的单词替换输入中输入的任何单词。这是字典:
slang = {'phone': 'dog and bone','queen': 'baked bean','suit': 'whistle and flute','money': 'bees and honey','dead': 'brown bread','mate': 'china plate','shoes': 'dinky doos','telly': 'custard and jelly','boots': 'daisy roots','road': 'frog and toad','head': 'loaf of bread','soup': 'loop the loop','walk': 'ball and chalk','fork': 'roast pork','goal': 'sausage roll','stairs': 'apples and pears','face': 'boat race'}
这是输出示例。
Sentence: I called the Queen on the phone
I called the baked bean on the dog and bone
我已经尝试编写该程序的代码,并且得到了它的输出结果(几乎)。我只是不知道如何问输入的单词是否在字典中,而不用小写字母替换大写的单词。
这是我的输出示例:
Sentence: I called the Queen on the phone
i called the baked bean on the dog and bone
这是我尝试的代码,我意识到这个问题的出现是因为我在开始时将句子设置为较低。在进入for循环之前,我曾尝试将'word'设置为较低,但这无法正常工作,因为直到for循环之前'word'都是未知的。
slang = {'phone': 'dog and bone','face': 'boat race'}
new_sentence = []
sentence = input("Sentence: ").lower()
words_list = sentence.split()
for word in words_list:
if word in slang:
replace = slang[word]
new_sentence.append(replace.lower())
if word not in slang:
new_sentence.append(word)
separator = " "
print(separator.join(new_sentence))
非常感谢您!
解决方法
您可以改用list comprehension
slang = {'phone': 'dog and bone','queen': 'baked bean',...}
Sentence = "I called the baked bean on the dog and bone"
print(" ".join(slang.get(x.lower(),x) for x in Sentence.split()))
I called the baked bean on the dog and bone
,
类似以下内容:
slang = {'phone': 'dog and bone','queen': 'baked bean'}
def replace_with_slang(sentence):
words = sentence.split(' ')
temp = []
for word in words:
temp.append(slang.get(word,word))
return ' '.join(temp)
print(replace_with_slang('I called the phone It was the queen '))