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

时间:2018-04-01 17:25:39

标签: python string python-3.x dictionary

我有以下句子

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"

我做错了什么?

4 个答案:

答案 0 :(得分:7)

这是一种方式。

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使用列表推导与生成器表达式进行marginally better

答案 1 :(得分:2)

你需要在split(' ')' '你的句子 - 如果你只是遍历一个字符串,你就会迭代字符:

a = "you don't need a dog"

for word in a:  # thats what you are using as input to your dict-key-replace
    print(word) # the single characters are never matched, thats why yours does not work.

输出:

y
o
u

d
o
n
'
t

n
e
e
d

a

d
o
g

阅读How to debug small programs

之后,请阅读How to split a string into a list?或使用jpp的解决方案。

答案 2 :(得分:2)

所有答案都是正确的,但是如果你的句子很长并且映射字典相当小,你应该考虑迭代字典的项目(键值对)并将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" }

for key, value in mapping.items():
    search = search.replace(key, value)

让我们尝试使用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" }

search = [search.replace(key, value) for key, value in mapping.items()][0]

让我们使用Python3列表理解。因此,我们获得了每个循环1.09μs的最快版本。

CLONE_VM

你看到了区别吗?对于您的短句,第一个和第三个代码的速度大致相同。但是句子(搜索字符串)越长,性能差异越明显。

结果字符串是:

  

'你不需要狗。但如果你喜欢狗,你应该考虑为自己买一只狗。还是一只猫?'

备注: str.replace也会替换长连接词中的出现次数。人们需要确保仅对完整单词进行替换。我猜有str.replace的选项。另一个想法是使用正则表达式作为explained in this posting,因为它们也处理较低和较高的情况。查找词典中的尾随空格不起作用,因为您不会在句子的开头或结尾处找到事件。

答案 3 :(得分:0)

这比你想象的要简单:

只需循环,如果dict1中有一个单词,则获取该键的值。

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

a = "you don't need a dog"

data=a.split()

for i,j in enumerate(data):
    if j in dict1:
        data[i]=dict1[j]
print(" ".join(data))

输出:

you do not need a dog