有一本缩略语字典,键是缩略语,值是缩略语的定义("TTYL","Talk To You Later")当用户输入包含超过1个缩写的内容时,我希望程序用定义替换这些缩写,作为对原始输入的补充。我让程序工作了,但只有一个缩写。我希望它能够处理一个字符串中的多个缩写。我相信解决方案与嵌套的for循环有关,但我不确定,需要一些帮助。
Python代码:
abbreviationsDictionary = {
"ADBA":"As Directed By Arborist",
"CRTS":"Crown Reduced To Shape",
"NWIC":"Noob Will Improve Company"
}
note = input("Enter note: ")
listOfWordsInNote = note.split()
updatedNote = ""
for key in abbreviationsDictionary:
for word in listOfWordsInNote:
if (key==word):
updatedNote = note.replace(key,abbreviationsDictionary[key])
print(updatedNote)
电流输出(仅适用于1个缩写):
Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever ADBA because he knows Noob Will Improve Company
期望输出值
Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever As Directed By Arborist because he knows Noob Will Improve Company
您的错误是使用
updatedNote = note.replace(key,abbreviationsDictionary[key])
因此,每次找到一个新键时,都要重新启动,并使用note(没有更改)
替换为:
note = note.replace(key,abbreviationsDictionary[key])
并打印(注):
mike将按照Arborist的指示去做任何事情,因为他知道Noob将改善公司
与其在输入字符串中替换,不如从用户输入中获取[whitespace delimited]令牌,然后使用一个简单的生成器来重建:
abbreviationsDictionary = {
"ADBA": "As Directed By Arborist",
"CRTS": "Crown Reduced To Shape",
"NWIC": "Noob Will Improve Company"
}
note = input("Enter note: ")
print(' '.join(abbreviationsDictionary.get(loin, loin) for loin in note.split()))