【发布时间】:2018-02-14 00:59:09
【问题描述】:
我有一个 Python 中引用不一致的列表,我正在尝试消除它们。如果 csv 文件中每行只有一组双引号,则类似下面的内容可以正常工作,但如果有多组(例如第四行(标题后的第三行数据)),则会被丢弃
我尝试了许多不同的方法,但我似乎总是以不正确的方式组合元素。
示例 csv:
First,Nickname,Last,Sport
Bill,Bats,Smith,Baseball
Tom,Kicks,Johnson,Soccer
"John,"Footy",Jacobsen,Football"
Mike,"Mikey",Jones,Basketball
我的代码:
import csv
with open('fake.csv', mode='r', encoding = 'utf-8') as infile:
reader = csv.reader(infile)
for line in reader:
if len(line) <4:
for i in range(0,len(line)):
line[i].strip('"')
line[i].replace('"', '')
print(line)
print(line[0] + line[2])
期望的输出:
['First', 'Nickname', 'Last', 'Sport']
FirstLast
['Bill', 'Bats', 'Smith', 'Baseball']
BillSmith
['Tom', 'Kicks', 'Johnson', 'Soccer']
TomJohnson
['John','Footy', 'Jacobsen', 'Football']
JohnJacobsen
['Mike', 'Mikey', 'Jones', 'Basketball']
MikeJones
我的输出:
['First', 'Nickname', 'Last', 'Sport']
FirstLast
['Bill', 'Bats', 'Smith', 'Baseball']
BillSmith
['Tom', 'Kicks', 'Johnson', 'Soccer']
TomJohnson
['John,Footy"', 'Jacobsen', 'Football"']
John,Footy"Football"
['Mike', 'Mikey', 'Jones', 'Basketball']
MikeJones
任何帮助将不胜感激
【问题讨论】:
-
Python 中的字符串是不可变的。如果有的话,你应该做
line[i]=line[i].strip('"')和replace一样。