4

I'm having some issues with my code:

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

Expected output = '1 you, how's things', '1, good thanks'

It currently does not replace any occurrences of hello. I'm wondering if my sentence loop is correct or not? Printing i after this prints out exactly what is in sentence.

5 Answers 5

4

I guess the word_list(try to rename the variable to word_dict, I think that is more appropriate) has lots of items,

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])

working example from 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']
Sign up to request clarification or add additional context in comments.

1 Comment

Python 3 renamed dict.iteritems() -> dict.items()!
2

The replacement occurs on a variable inside the loop So nothing is changed in the sentence list To fix this make a new list with the changed items in it

word_list = { "hello" : "1"}

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

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

Another way with map

word_list = { "hello" : "1"}

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

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

Another way with a list comprehension

word_list = { "hello" : "1"}

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

for key, value in word_list.items():
  newlist=[x.replace(key,value) for x in sentence]
print newlist

note: updated for python3, thanks @MGM

1 Comment

Python 3 renamed dict.iteritems() -> dict.items()!
0

I ran your code verbatim and it worked, but only prints the last "i". If you move the print into the for loop you get what you expected.

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

output:

1 you, hows things
1, good thanks

1 Comment

Python 3 renamed dict.iteritems() -> dict.items()!
0

Using regex:

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

1 Comment

This, too, can replace words that are parts of other words. Better use \b for word boundaries.
0

Using str.replace is problematic, as a word could be a part of another word. Better use re.sub with regular expression \b\w+\b, with \b being "word boundary", and use a callback function to get the replacement from the dictionary (or the word itself, if it is not in the dict).

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

Also, not that by assigning to i within the loop, you are only changing the value bound to the variable i; you are not changing the string in the list! For this, you have to assign to the list element at that index, or use a list comprehension, as in my example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.