替换字典中列表中的字符串

用户名

我的代码存在一些问题:

word_list = { "hello" : "1", "bye" : "2"}

sentence= ['hello you, hows things', 'hello, good thanks']

for key, value in word_list.iteritems():
   for i in sentence:
       i = i.replace(key, value)
print i

预期输出= '1 you, how's things''1, good thanks'

目前,它不能代替的任何出现hello我想知道我的句子循环是否正确?打印i完后,将完全打印出其中的内容sentence

吉廷

我猜word_list(尝试将变量重命名为word_dict,我认为更合适)有很多项目,

for index, data in enumerate(sentence):
    for key, value in word_list.iteritems():
        if key in data:
            sentence[index]=data.replace(key, word_list[key])

来自的工作示例 ipython

In [1]: word_list = { "hello" : "1", "bye" : "2"}

In [2]: sentence = ['hello you, hows things', 'hello, good thanks']

In [3]: for index, data in enumerate(sentence):
   ...:         for key, value in word_list.iteritems():
   ...:                 if key in data:
   ...:                         sentence[index]=data.replace(key, word_list[key])
   ...:             

In [4]: sentence
Out[4]: ['1 you, hows things', '1, good thanks']

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章