2

我收到此错误:

Traceback (most recent call last):
  File "/Users/Rose/Documents/workspace/METProjectFOREAL/src/test_met4.py", line 79, in   <module>
    table_list.append(table_template % art_temp_dict)
KeyError: 'artifact4'

从此代码:

artifact_groups = grouper(4, html_list, "")  

for artifact_group in artifact_groups:
    art_temp_dict={}
     for artifact in artifact_group:
         art_temp_dict["artifact"+str(artifact_group.index(artifact)+1)] = artifact

    table_list.append(table_template % art_temp_dict)

这是 CSV 的示例:

7 17.8 21.6 cm)","74.51.2819","4977" "artifact4978.jpg","H. 6 3/8 x 14 1/2 x 5 1/4 英寸 (16.2 x 36.8 x 13.3 厘米)","74.51.2831","4978"

我知道 KeyError 表示“artifact4”不存在,但我不知道为什么 - 我正在从一个包含近 6,000 条记录的大型 CSV 文件中获取数据。任何建议都非常感谢!

4

2 回答 2

3

如果您曾经遇到过 CSV 的第四列与较早的列之一具有相同值的情况,index则将产生较早的匹配并且artifact4永远不会被填充。改用这个:

 for i, artifact in enumerate(artifact_group):
     art_temp_dict["artifact"+str(i+1)] = artifact
于 2013-06-11T21:10:32.033 回答
3

csv.DictReader您可以通过使用而不是使用csv.reader然后尝试dict从每一行生成一个来使这更简单:

>>> s='''"artifact4971.jpg","H. 17 1/2 x 16 1/2 x 5 1/2 in. (44.5 x 41.9 x 14 cm)","74.51.2648","4971"
... "artifact4972.jpg","Overall: 5 1/2 x 3 3/4 x 4 in. (14.0 x 9.5 x 10.2 cm)","74.51.2592","4972"
... "artifact4973.jpg","Overall: 6 5/8 x 7 1/4 x 1 1/4 in. (16.8 x 18.4 x 3.2 cm)","74.51.2594","4973"'''
>>> reader = csv.DictReader(s.splitlines(), 
...                         ('artifact1', 'artifact2', 'artifact3', 'artifact4'))
>>> list(reader)
[{'artifact1': 'artifact4971.jpg',
  'artifact2': 'H. 17 1/2 x 16 1/2 x 5 1/2 in. (44.5 x 41.9 x 14 cm)',
  'artifact3': '74.51.2648',
  'artifact4': '4971'},
 {'artifact1': 'artifact4972.jpg',
  'artifact2': 'Overall: 5 1/2 x 3 3/4 x 4 in. (14.0 x 9.5 x 10.2 cm)',
  'artifact3': '74.51.2592',
  'artifact4': '4972'},
 {'artifact1': 'artifact4973.jpg',
  'artifact2': 'Overall: 6 5/8 x 7 1/4 x 1 1/4 in. (16.8 x 18.4 x 3.2 cm)',
  'artifact3': '74.51.2594',
  'artifact4': '4973'}]

如果您真的想自己构建每一行 dict,那么使用 dict 理解就更难出错。

声明式结构强烈鼓励您正确考虑这一点。如果你知道enumerate你可能会写这样的东西:

 art_temp_dict={'artifact'+str(i+1): artifact
                for i, artifact in enumerate(artifact_group)}

......如果不是,像这样的东西 - 更丑陋,但仍然正确:

 art_temp_dict={'artifact'+str(i+1): artifact_group[i]
                for i in len(artifact_group)}

…而不是试图通过搜索来恢复索引。

于 2013-06-11T21:17:37.770 回答