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

时间:2013-07-08 21:18:03

标签: python python-2.7

我正在尝试替换csv文件中的多个字符串。这些字符串可能没有特定的列。

我在这个主题Python replace multiple strings中使用了wordpress条目。我以为我有CSV模块,但我想这没有替换功能。我尝试了下面的内容,但它只替换了第一本字典。它必须首先在第一个字典中进行输入,第二个字典的顺序无关紧要。

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)

有人可以帮我吗?甚至更好的csv模块版本?

谢谢, B0T

修改

这是答案后的最终代码。它奏效了。

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)

1 个答案:

答案 0 :(得分:1)

嗯......这对我来说很好。

我正在运行python 2.7.3

尝试从包含“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)

运行后,file2.csv包含x23dbc

也许我的测试案例太简单了。你怎么样告诉我们你在file1.csv中有什么,你期望在file2.csv中看到什么,以及你在file2.csv中看到了什么。