adsqw qwe
adsqw qwe

Reputation: 49

Python replacing keys with values in dictionary

I have a dictionary as:['snow side':'ice','tea time':'coffee'].I need to replace the key with the values in the text file.

I have a text as :

I seen area at snow side.I had tea time.
I am having good friends during my teatime.

To be converted to:

I seen area at ice.I had coffee.
I am having good friends during my coffee.

Coding:

import re
dict={'snow side':'ice','tea time':'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
    for key,values in dict:
        matched = re.search(r'\.\(.*?\)', key)
        replaced = re.sub(r'\.\(.*?\)', '.(' + values + ')', values)
        f.seek(0)
        f.write(replaced)
        f.truncate()

Please help me to fix my code!Answers will be appreciated!

Upvotes: 1

Views: 413

Answers (2)

starrify
starrify

Reputation: 14731

This is expected to work:

d = {'snow side': 'ice', 'tea time': 'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
    for key in d:
        content.replace(key, d[key])
    f.seek(0)
    f.write(content)
    f.truncate()

Also, do not override built-in names like dict.

Upvotes: 1

Anshul Goyal
Anshul Goyal

Reputation: 76847

I don't think regular expressions are needed here, a simple replace should work as well

>>> text = """I seen area at snow side.I had tea time.
... I am having good friends during my teatime."""
>>> 
>>> dict={'snow side':'ice','teatime':'coffee'}
>>> 
>>> for key in dict:
...     text = text.replace(key, dict[key])
... 
>>> print text
I seen area at ice.I had tea time.
I am having good friends during my coffee.

So, your original example changes to:

dict={'snow side':'ice','tea time':'coffee'}
with open('text3.txt', 'r+') as f:
    content = f.read()
for key in dict:
    content = content.replace(key, dict[key])
with open('text3.txt', 'w') as f:
    f.write(content)

Upvotes: 1

Related Questions