我有以下句子
a = "you don't need a dog"
和一本字典
dict = {"don't": "do not" }
但是我不能使用字典来使用下面的代码映射句子中的单词:
''.join(str(dict.get(word, word)) for word in a)
输出:
"you don't need a dog"
我究竟做错了什么?
原文由 A.Papa 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有以下句子
a = "you don't need a dog"
和一本字典
dict = {"don't": "do not" }
但是我不能使用字典来使用下面的代码映射句子中的单词:
''.join(str(dict.get(word, word)) for word in a)
输出:
"you don't need a dog"
我究竟做错了什么?
原文由 A.Papa 发布,翻译遵循 CC BY-SA 4.0 许可协议
所有答案都是正确的,但如果你的句子很长而映射字典很小,你应该考虑迭代字典的项目(键值对)并将 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 的选项。另一个想法是使用正则表达式, 正如这篇文章中所解释的那样, 因为它们也处理小写和大写。查找字典中的尾随空格将不起作用,因为您不会在句子的开头或结尾找到匹配项。
原文由 Matthias 发布,翻译遵循 CC BY-SA 3.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3.1k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
这是一种方法。
解释
d
而不是dict
。str.split
按空格分割。str
包裹在已经是字符串的值周围。str.join
与生成器表达式相比,列表理解 稍微好一些。