简体   繁体   English

替换csv文件中的多个字符串

[英]Replace multiple strings in csv file

I am trying to replace multiple strings in a csv file. 我正在尝试替换csv文件中的多个字符串。 There is no specific column these strings may be in. 这些字符串可能没有特定的列。

I used the example in this thread Python replace multiple strings , the wordpress entry. 我在此线程中使用的示例Python替换了多个字符串 (wordpress条目)。 I thought I had it with the CSV module but I guess that does not have a replace function. 我以为我在CSV模块中有它,但是我想它没有替换功能。 I tried the below, but it only does the replace from the first dictionary. 我尝试了下面的方法,但是它仅从第一个字典进行替换。 It has to do the entries in the first dictionary first, the order of the second dictionary doesn't matter as much. 它必须先在第一个词典中输入条目,第二个词典的顺序无关紧要。

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

f_dic = {'-':' '}
s_dic = {'  ':' ','   ':' ','SASD D':'SASD-D','DC W':'DC-W',r'PROD\s\d':r'PROD\d'}

with open('file1.csv','r') as f:
    text=f.read()
    with open('file2.csv','w') as w:
        text=replace_all(text,f_dic)
        text=replace_all(text,s_dic)
        w.write(text)

Can someone help me with this? 有人可以帮我弄这个吗? or even better a csv module version of this? 甚至更好的csv模块版本?

Thanks, B0T 谢谢,B0T

EDIT 编辑

This is my final code after the answer. 这是答案后的最终代码。 It worked. 有效。

import re

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

f_dic = {'-':' '}
s_dic = {'  ':' ','   ':' ','SASD D':'SASD-D','DC W':'DC-W'}
t_dic = {'  ':' '}

with open('file1.csv','r') as f:
    text=f.read()
    text=replace_all(text,f_dic)
    text=replace_all(text,s_dic)
    text=replace_all(text,t_dic)
    text=re.sub(r'PROD\s(?=[1-9])',r'PROD',text)

with open('file2.csv','w') as w:
    w.write(text)

Hmm... this worked fine for me. 嗯...这对我来说很好。

I'm running python 2.7.3 我正在运行python 2.7.3

try a minimal test case starting with file1.csv containing "123abc": 请尝试以包含“ 123abc”的file1.csv开头的最小测试用例:

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

f_dic = {'a':'d'}
s_dic = {'1':'x'}

with open('file1.csv','r') as f:
    text=f.read()
    with open('file2.csv','w') as w:
        text=replace_all(text,f_dic)
        text=replace_all(text,s_dic)
        print text
        w.write(text)

After running, file2.csv contained x23dbc 运行后,file2.csv包含x23dbc

Perhaps my test case was too simple. 也许我的测试案例太简单了。 How about you give us what you had in file1.csv, what you expected to see in file2.csv and what you actually saw in file2.csv. 您如何向我们提供您在file1.csv中拥有的内容,希望在file2.csv中看到的内容以及在file2.csv中实际看到的内容。

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

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