简体   繁体   English

使用 Python 搜索和替换 a.CSV 文件中的多个名称

[英]Search & Replace several Names in a .CSV File using Python

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.我使用 python 从两个不同的站点抓取数据,得到两个。CSV 文件(感谢 SIM)现在我想比较数据。 The problem is, that the Site i get the data from, are calling some names different eg问题是,我从中获取数据的站点正在调用一些不同的名称,例如

Chelsea FC instead FC Chelsea or FSV Mainz instead 1. FSV Mainz 05 and many more names i have to replace. Chelsea FC代替FC ChelseaFSV Mainz代替1. FSV Mainz 05以及我必须替换的更多名称。

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!非常感谢!

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对于更复杂的文本操作,请尝试使用re (正则表达式)模块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM