我有一个CSV文件,其中包含我要编辑的名称列表。我正在尝试进行多项更改。使用下面的代码打开时,打印的csv显示如下:
with open ('wedding table cards.csv',newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
['Mr. and Mrs. Scott Summers']
['Ms. Lorna Dane']
['Mr. Hank McCoy and Ms. Ororo Munroe']
['Mr. Logan Wolverine']
['Mr. and Mrs. Warren Worthington']
['Ms. Anna Marie and Mr. Remy Lebeau']
以下是我需要帮助的行动。不确定我是否应该使用Regex或其他功能来解决这些问题。
对于#1,这是我到目前为止所尝试的。它的工作原理除了它为第二列增加了一个额外的空间。
with open('wedding table cards.csv') as inf:
with open('test_1.csv','w') as outf:
for line in inf:
outf.write('Mr. and Mrs.'.join(line.split('Mr. and Mrs.')))
答案 0 :(得分:0)
一种方式:
if 'Mr. and Mrs.' in line:
line = 'Mr. and Mrs.,' + line[13:]
elif 'Mr.' in line or 'Ms.' in line:
line = line[4:]
elif ' and ' in line:
line = ','.join(line.split(' and '))