在 csv 文件中,我试图用其他字符替换某些字符。
我当前的代码与此类似:
import csv
set1 = set('abc')
set2 = set('def')
set3 = set('ghi')
with open(path, 'r') as input, open(path2, 'w') as output:
reader = csv.reader(input)
writer = csv.writer(output)
for row in reader:
newrow = row
newrow = [''.join('x' if c in set1 else c for c in item) for item in newrow]
newrow = [''.join('y' if c in set2 else c for c in item) for item in newrow]
newrow = [''.join('z' if c in set3 else c for c in item) for item in newrow]
writer.writerow(newrow)
在这个例子中,我只使用了三个生成器表达式,但很容易不止这些。
有谁知道这样做的正确方法?我担心这种结构可能不是最快的(当然看起来也不是最优的)。