csv ファイル内の複数の文字列を置き換えようとしています。これらの文字列が含まれる特定の列はありません。
このスレッドPython replace multiple strings、wordpress エントリの例を使用しました。私はCSVモジュールでそれを持っていると思っていましたが、それは置換機能を持っていないと思います. 以下を試しましたが、最初の辞書からの置換のみを行います。最初のディクショナリのエントリを最初に実行する必要があり、2 番目のディクショナリの順序はそれほど重要ではありません。
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)