Red Security

Full Version: Dictionary Use in real life example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: BFMMlbcQvml9HSqXcvNp]
Change a word in text File using Dictionary:
                     Hi guys, I hope you are doing well. In today’s thread I am going to show you how you can use a python dictionary data structure to change a word in a text file so without wasting any time let’s get started. First of all we have to load our text file in our program
 
Code:
file = open('SomeText.txt')


After that now we will store it into a string named ‘text’

Code:
text = file.read()

Now we will create a dictionary that stores the existing word as key and the word that we want to add as value just like this..

Code:
d = {}

d['left'] = '__left__'
d['right'] = '__Right__'
d['printPicnic()'] = '__This is A function()__'


So now we want to change left with ‘__left__’  and so on. You can change the values by your wish and now we will replace these words in our string ‘text’..

Code:
for key in d:
    text = text.replace(key, d[key])

And now if we want to print the text we will get the new string..

Code:
print(text)

So the whole code will be like this 


Code:
file = open('SomeText.txt')
text = file.read()

d = {}

d['left'] = '__left__'
d['right'] = '__Right__'
d['printPicnic()'] = '__This is A function()__'

for key in d:
    text = text.replace(key, d[key])

print(text)

The result of this code will look like this...

[attachment=402]

So that's it for now. If you have any questions related to python you can ask in the comment section or directly DM me. Thank you!

"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"