我有一个作业问题,用字典中的其他单词替换用户输入。当我编写一个for循环时,可以看到第一次迭代正确地替换了关键字,但是第二次迭代替换了字典中的下一个关键字。问题是第一次迭代没有保存或被覆盖。我不确定是什么原因导致的,并且我的代码可能会改变什么?
def main():
#Get a phrase from the user
print('')
phrase = input('Enter a phrase: ')
checkPhase(phrase)
def checkPhase(phrase):
#Define the simple thesaurus
thesaurus = {
'Happy': 'Glad',
'sad' : 'bleak'
}
for key in thesaurus:
old_word = key
new_word = thesaurus[key]
print(old_word) #used to help troubleshoot
print(new_word) #used to help troubleshoot
new_phrase = phrase.replace(old_word,new_word)
print(new_phrase) #used to show phrase after each iteration for troubleshooting
print(new_phrase)
main()
答案 0 :(得分:1)
问题是结果在循环中不断被覆盖。而是在循环之前初始化结果:
def checkPhase(phrase):
#Define the simple thesaurus
thesaurus = {
'Happy': 'Glad',
'sad' : 'bleak'
}
new_phrase = phrase # <-- init
for key in thesaurus:
old_word = key
new_word = thesaurus[key]
print(old_word) #used to help troubleshoot
print(new_word) #used to help troubleshoot
new_phrase = new_phrase.replace(old_word,new_word) # <-- modify
print(new_phrase) #used to show phrase after each iteration for troubleshooting
print(new_phrase)