所有答案都是正确的,但是如果您的句子很长并且映射字典很小,您应该考虑迭代字典的项目(键值对)并将 str.replace 应用于原始句子.
其他人建议的代码。每个循环需要 6.35 µs。
%%timeit
search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?"
mapping = {"don't": "do not" }
search = ' '.join([mapping.get(i, i) for i in search.split()])
让我们尝试使用 str.replace 代替。每个循环需要 633 ns。
%%timeit
search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?"
mapping = {"don't": "do not" }
for key, value in mapping.items():
search = search.replace(key, value)
让我们使用 Python3 列表推导。所以我们得到了最快的版本,每个循环需要 1.09 µs。
%%timeit
search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?"
mapping = {"don't": "do not" }
search = [search.replace(key, value) for key, value in mapping.items()][0]
你看出区别了吗?对于您的短句,第一个和第三个代码的速度大致相同。但是句子(搜索字符串)越长,性能上的差异就越明显。
结果字符串是:
'你不需要狗。但如果你喜欢狗,你应该考虑给自己养一只。还是一只猫?'
备注: str.replace 也会替换长连接词中的出现。需要确保仅对完整单词进行替换。我想有 str.replace 的选项。另一个想法是使用正则表达式作为explained in this posting,因为它们也处理大小写。查找字典中的尾随空格不起作用,因为您不会在句子的开头或结尾找到匹配项。