简体   繁体   English

Python按行迭代搜索和替换CSV

[英]Python search and replace in CSV iteratively by line

I'm looking to extend the Python solution found here: PowerShell is slow (much slower than Python) in large Search/Replace operation? 我想扩展在这里找到的Python解决方案: 在大型“搜索/替换”操作中,PowerShell速度慢(比Python慢​​得多)?

To replace string across CSV files I use: findReplace("c:/temp/csv", "Search String", "Replace String", "*.csv") 要在CSV文件中替换字符串,请使用: findReplace("c:/temp/csv", "Search String", "Replace String", "*.csv")

What I'd like to be able to do is have "Search" and "Replace" be a list of terms. 我想做的是将“搜索”和“替换”作为术语列表。 I cannot use re as the term is unknown prior to finding it manually. 我无法使用re,因为在手动找到它之前该术语是未知的。 However, since the CSV files have the same structure and may have the same string values finding the term once is sufficient to automate the process. 但是,由于CSV文件具有相同的结构,并且可能具有相同的字符串值,因此找到该术语一次就足以自动化该过程。

Any insight on best approach would be greatly appreciated. 任何对最佳方法的见解将不胜感激。

You mentioned lists, so I'm guessing you have two lists like this: 您提到了列表,所以我猜您有两个这样的列表:

findlist = ['hey', 'hello', 'hi']
replacelist = ['bye', 'see ya', 'brb']

You can load them into a dictionary with this: 您可以使用以下命令将它们加载到字典中:

rep = dict(zip(findlist, replacelist))

Then the function can be written: 然后可以编写该函数:

for item in findlist:
    findReplace("c:/temp/csv", item, rep[item], "*.csv")

I'm definitely a StackOverflow newbie, but it would help if you provided sample inputs and the desired outputs. 我绝对是StackOverflow的新手,但是如果您提供示例输入和所需的输出,则将有所帮助。 Otherwise we'll just guess, and the answer may not be what you want. 否则,我们只会猜测,答案可能不是您想要的。

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

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