当我运行此代码来编辑我的 CSV 文件时,即使我的字典中有字符串,也只有部分字符串被替换。
import re
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
bottle = "vial jug canteen urn jug33"
transport = "car automobile airplane scooter"
mydict = {}
for word in bottle.split():
mydict[word] = 'bottle'
for word in transport.split():
mydict[word] = 'transport'
print(mydict) # test
with open('replacesample.csv','r') as f:
text=f.read()
text=replace_all(text,mydict)
text=re.sub(r'PROD\s(?=[1-9])',r'PROD',text)
with open('file2.csv','w') as w:
w.write(text)
例如,如果我的字符串 CSV 是这样的:
jug
canteen
urn
car
automobile
swag
airplane
jug33
我的最终结果是:
bottle
bottle
bottle
transport
transport
swag
transport
bottle33
我该如何解决?
预期的:
bottle
bottle
bottle
transport
transport
swag
transport
bottle