Reputation: 25
i've wrote a code that solves the task, but i doesnt feel well. It is like hit a nail in the wall using a stone instead a hammer.
The Task:
I scrape data from two different Sites using python with gets me two .CSV Files (thx to SIM) and now i want to compare the data. The problem is, that the Site i get the data from, are calling some names different e.g.
Chelsea FC
instead FC Chelsea
or FSV Mainz
instead 1. FSV Mainz 05
and many more names i have to replace.
Here is the code i made:
text = open("input.csv", "r")
text = ''.join([i for i in text]) \
.replace("Chelsea FC", "FC Chelsea")
x = open("output1.csv","w")
x.writelines(text)
x.close()
text = open("output1.csv", "r")
text = ''.join([i for i in text]) \
.replace("FSV Mainz", "1. FSV Mainz 05")
x = open("output_final.csv","w")
x.writelines(text)
x.close()
The Problem is that i have to write a file after every single name i have changed. I mean it does the Job but it hurts my feelings.
Can you guide me the way to better code, please? Attention: I am an absolute beginner!
Thank you very much!
Upvotes: 0
Views: 55
Reputation: 1143
This is one simple way to do
with open("input.csv", "r") as file:
text = file.read()
text = text.replace("Chelsea FC", "FC Chelsea")
text = text.replace("FSV Mainz", "1. FSV Mainz 05")
# more replaces...
with open("output_final.csv", "w") as x:
x.write(text)
For more complex text manipulation, try using re
(regular expression) module
Upvotes: 1