我有一个像csv:
"Equipment","LNKEQP","METAST","METSER","MODSTA","METEOD" "HLL_POS_00098",1,1,0,0,0 "TOY_GAT_00003",0,0,0,3,0 "NAT_POS_00010",0,3,0,3,0 "NAT_GAT_00002",0,0,0,0,0 "NAT_GAT_00001",0,0,0,4,0 A machine A is unavailable
我使用代码将csv文件读作:
reader = csv.DictReader(f)
s=[]
for row in reader:
但该行不包含"机器A不可用",如何获取此行和输出作为此示例:
'METEOD': '0', 'MODSTA': '0', 'METSER': '0', 'LNKEQP': '0', 'METAST': '0', 'Equipmnt': 'NAT_VCF_00001'
'METEOD': '0', 'MODSTA': '0', 'METSER': '0', 'LNKEQP': '1', 'METAST': '1', 'Equipment': 'NAT_TVM_00002'
A machine A is unavailable
感谢您的帮助
答案 0 :(得分:4)
在解析之前删除有问题的行:
import csv
from StringIO import StringIO
i = """"Equipment","LNKEQP","METAST","METSER","MODSTA","METEOD"
"HLL_POS_00098",1,1,0,0,0
"TOY_GAT_00003",0,0,0,3,0
"NAT_POS_00010",0,3,0,3,0
"NAT_GAT_00002",0,0,0,0,0
"NAT_GAT_00001",0,0,0,4,0
A machine A is unavailable
"""
# Take only those lines that contain a comma.
j = "".join([line for line in StringIO(i).readlines() if ',' in line])
# Parse the taken lines as CSV.
reader = csv.reader(StringIO(j))
for line in reader:
print line
输出:
['Equipment', 'LNKEQP', 'METAST', 'METSER', 'MODSTA', 'METEOD']
['HLL_POS_00098', '1', '1', '0', '0', '0']
['TOY_GAT_00003', '0', '0', '0', '3', '0']
['NAT_POS_00010', '0', '3', '0', '3', '0']
['NAT_GAT_00002', '0', '0', '0', '0', '0']
['NAT_GAT_00001', '0', '0', '0', '4', '0']