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
.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With