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

时间:2016-02-10 11:47:32

标签: python

我的代码存在一些问题:

;

预期输出= ,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中的内容。

5 个答案:

答案 0 :(得分:2)

我想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']

答案 1 :(得分:0)

替换发生在循环内的变量上 因此var table = $('table.container-fluid').dataTable({ // ... skipped ... }); table.api().ajax.url(newURL).load(); 列表中没有任何更改 要解决此问题,请在其中添加包含已更改项目的新列表

sentence

地图的另一种方式

word_list = { "hello" : "1"}

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

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

列表理解的另一种方式

word_list = { "hello" : "1"}

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

for key, value in word_list.iteritems():
  newlist=map(lambda x: x.replace(key,value), sentence)
print newlist

答案 2 :(得分:0)

使用onclick是有问题的,因为单词可能是另一个单词的一部分。最好将re.sub与正则表达式str.replace一起使用,\b\w+\b为"字边界",并使用回调函数从字典中获取替换(或单词本身,如果它不在词典中。)

\b

此外,不是通过在循环中分配>>> word_list = { "hello" : "1", "bye" : "2", 'you': "3"} >>> sentence= ['hello you, hows things', 'you is not yourself', 'hello, good thanks'] >>> [re.sub(r'\b\w+\b', lambda m: word_list.get(m.group(), m.group()), s) for s in sentence] ['1 3, hows things', '3 is not yourself', '1, good thanks'] ,而是仅更改绑定到变量i的值;你是更改列表中的字符串!为此,您必须在该索引处分配list元素,或使用列表推导,如我的示例所示。

答案 3 :(得分:0)

我逐字地运行你的代码并且它有效,但只打印最后一个" i"。如果将打印件移动到for循环中,则可以获得预期效果。

word_list = { "hello" : "1"}

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, hows things
1, good thanks

答案 4 :(得分:0)

使用正则表达式:

>>> word_list = { "hello" : "1", "bye" : "2"}
>>> sentence= ['hello you, hows things', 'hello, good thanks']
>>> [re.sub('|'.join(word_list.keys()), lambda x: word_list[x.group()], i) for i in sentence]
['1 you, hows things', '1, good thanks']
>>>