搜索替换 csv 文件中的文本

初学者尝试使用Python 3.4.2查找并替换CSV文件中的文本,目标是遍历Input.csv的每一行,将最后一列的文本替换为list.csv中匹配的字符串。最终通过集算器的SPL脚本实现无需循环的文本结构化计算,完成文件内容更新。

【问题】

I just started with Python 3.4.2 and trying to find and replace text in csv file.

In Details,Input.csvfile contain below line:

0,0,0,13,.\New\_Path-1.1.12\Impl\Appli\Library\Module_RM\Code\src\Exception.cpp
0,0,0,98,.\Old_Path-1.1.12\Impl\Appli\Library\Prof_bus\Code\src\Wrapper.cpp
0,0,0,26,.\New_Path-1.1.12\Impl\Support\Custom\Vital\Code\src\Interface.cpp
0,0,0,114,.\Old_Path-1.1.12\Impl\Support\Custom\Cust\Code\src\Config.cpp

I maintained my strings to be searched in other file namedlist.csv

Module_RM
Prof_bus
Vital
Cust

Now I need to go through each line ofInput.csvand replace the last column with the matched string.

So my end result should be like this:

0,0,0,13,Module_RM
0,0,0,98,Prof_bus
0,0,0,26,Vital
0,0,0,114,Cust

I read the input files first line as a list. So text which i need to replace came inline[4]. I am reading each module name in thelist.csvfile and checking if there is any match of text inline[4]. I am not able to make thatifconditiontrue. Please let me know if it is not a proper search.

import csv
import re
with open("D:\\My_Python\\New_Python_Test\\Input.csv") as source, open("D:\\My\_Python\\\New_Python_Test\\List.csv") as module_names, open("D:\\My_Python\\New_Python_Test\\Final_File.csv","w",newline="") as result:
reader=csv.reader(source)
module=csv.reader(module_names)
writer=csv.writer(result)
#lines=source.readlines()
for line in reader:
for mod in module_names:
 if any(\[mod in s for s in line\]):
 line.replace(reader\[4\],mod)
 print ("YES")
 writer.writerow("OUT")
 print (mod)
module_names.seek(0)
lines=reader

Please guide me to complete this task.

Thanks for your support!

楼主自己解答了:

import csv
with open("D:\\My_Python\\New_Python_Test\\Input.csv") as source, open("D:\\My_Python\\New_Python_Test\\List.csv") as module_names, open("D:\\My_Python\\New_Python_Test\\Final_File.csv","w",newline="") as result:
 reader=csv.reader(source)
 module=csv.reader(module_names)
 writer=csv.writer(result)
 flag=False
 for row in reader:
 i=row[4]
 for s in module_names:
 k=s.strip()
 if i.find(k)!=-1 and flag==False:
 row[4]=k
 writer.writerow(row)
 flag=True
 module_names.seek(0)
 flag=False

【回答】

文本的结构化计算用集算器做会更独立些,不用写循环,SPL 脚本如下:

A
1=file("D:\\input.csv").import@c()
2=file("D:\\list.csv").import()
3=A1.run(_5=A2.select@1(pos(A1.#5,#1)).(#1))
4=file("D:\\result.csv").export(A1;",")

A3:从 A2 中查询满足条件的记录赋值给 A1 的 _5 字段

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值