如何使用字典映射替换字符串中的单词 [英] How to replace words in a string using a dictionary mapping

查看:48
本文介绍了如何使用字典映射替换字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一句话

a = "you don't need a dog"

和一本字典

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

但是我不能使用字典使用以下代码映射句子中的单词:

But I can't use the dictionary to map words in the sentence using the below code:

''.join(str(dict.get(word, word)) for word in a)

输出:

"you don't need a dog"

我在做什么错了?

推荐答案

这是一种方法.

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与列表生成器相比,与生成器表达式相比,略胜一筹.
  • Never name a variable after a class, e.g. use d instead of dict.
  • Use str.split to split by whitespace.
  • There is no need to wrap str around values which are already strings.
  • str.join works marginally better with a list comprehension versus a generator expression.

这篇关于如何使用字典映射替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆