如何使用字典映射替换字符串中的单词

新手上路,请多包涵

我有以下句子

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 许可协议

阅读 675
2 个回答

这是一种方法。

 a = "you don't need a dog"

d =  {"don't": "do not" }

res = ' '.join([d.get(i, i) for i in a.split()])

# 'you do not need a dog'

解释

  • 永远不要在类之后命名变量,例如使用 d 而不是 dict
  • 使用 str.split 按空格分割。
  • 不需要将 str 包裹在已经是字符串的值周围。
  • str.join 与生成器表达式相比,列表理解 稍微好一些

原文由 jpp 发布,翻译遵循 CC BY-SA 3.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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏