2
我想使用csv.DictReader读取TSV文件,但是,读者报告错误的字段数。当我看着里面,我发现这不是分裂的分隔符正常(我证实str.split(delimiter)
和awk -F 'delim'
python3的csv.DictReader没有像预期的那样通过分隔符分割记录
from pprint import pprint
import csv
import sys, os
keys = ['id', 'src', 'src_len', 'sys1_o', 'sys1_b', 'sys1_l',
'sys2_o', 'sys2_b', 'sys2_l', 'sys3_o', 'sys3_b', 'sys3_l', 'x']
# get this data from https://gist.github.com/thammegowda/95613b203a442fbe72fc5b51af491367
my_data = """segment-22 Kture . 27 Thutaalchisu. - 33 Koture. - 27 Th jump. - 33 3
segment-23 ‘Yunker . 7 "said. - 8 ‘Yunker. - 7 "said. - 8 1"""
tmp_file = "tmp.tsv"
with open(tmp_file, 'w', encoding='utf-8') as f:
f.write(my_data)
def read_recs_csv(path):
with open(path, 'rt', encoding='utf-8') as f:
rdr = csv.DictReader(f, fieldnames=keys, delimiter='\t')
for rec in rdr:
yield(dict(rec))
def read_recs_raw(path):
with open(path, 'rt', encoding='utf-8') as f:
for line in f:
rec = dict(zip(keys, line.strip().split('\t')))
yield(rec)
print("Reading through CSV DictReader ")
pprint(list(read_recs_csv(tmp_file)))
print("Reading directly")
pprint(list(read_recs_raw(tmp_file)))
# Debug
print(sys.version_info)
print(os.environ['LANG'])
输出:
Reading through CSV DictReader
[{'id': 'segment-22',
'src': 'Kture .',
'src_len': '27',
'sys1_b': '-',
'sys1_l': '33',
'sys1_o': 'Thutaalchisu.',
'sys2_b': '-',
'sys2_l': '27',
'sys2_o': 'Koture.',
'sys3_b': '-',
'sys3_l': '33',
'sys3_o': 'Th jump.',
'x': '3'},
{'id': 'segment-23',
'src': '‘Yunker .',
'src_len': '7',
'sys1_b': '-',
'sys1_l': '8',
'sys1_o': 'said.\t-\t8\t‘Yunker.\t-\t7\tsaid.',
'sys2_b': None,
'sys2_l': None,
'sys2_o': '1',
'sys3_b': None,
'sys3_l': None,
'sys3_o': None,
'x': None}]
Reading directly
[{'id': 'segment-22',
'src': 'Kture .',
'src_len': '27',
'sys1_b': '-',
'sys1_l': '33',
'sys1_o': 'Thutaalchisu.',
'sys2_b': '-',
'sys2_l': '27',
'sys2_o': 'Koture.',
'sys3_b': '-',
'sys3_l': '33',
'sys3_o': 'Th jump.',
'x': '3'},
{'id': 'segment-23',
'src': '‘Yunker .',
'src_len': '7',
'sys1_b': '-',
'sys1_l': '8',
'sys1_o': '"said.',
'sys2_b': '-',
'sys2_l': '7',
'sys2_o': '‘Yunker.',
'sys3_b': '-',
'sys3_l': '8',
'sys3_o': '"said.',
'x': '1'}]
sys.version_info(major=3, minor=6, micro=1, releaselevel='final', serial=0)
en_US.UTF-8
注:样本数据张贴在a gist。如果标签被空格替换,请下载它
你能提供一个你的csv内容的例子吗? – asongtoruin
注意只提供了12个密钥,因为有13列,读者添加一个额外的'None'键来分组其他值。那是故意的吗? –
@ Jean-FrançoisFabre是的,我只是想忽略其他键 –