[英]Replacing multiple words in string from a dictionary
有一个缩写字典,键是缩写,值是它的定义(“TTYL”、“稍后再谈”)。 当用户输入超过 1 个 abbreviation 的内容时,我想要一个程序用定义替换缩写作为原始输入的补充。 我让程序正常工作,但只有 1 个缩写。 我希望它能够处理字符串中超过 1 个的缩写。 我相信该解决方案与嵌套的 for 循环有关,但是我不确定并且需要一些帮助。
蟒蛇代码:
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])
并打印(注):
迈克将按照 Arborist 的指示做任何事情,因为他知道 Noob 会改善公司
与其替换输入字符串,不如从用户输入中获取 [空格分隔] 标记,然后使用简单的生成器进行重构:
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()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.