0

我有一个名为 beers.csv 的 csv 文件,我正在尝试从中读取 4 列 ( brewery_name, beer_style, beer_name, beer_abv),它们都是列标题。我有以下代码:

import csv

csvFile = "beers.csv"
csvData = csv.reader(csvFile, delimiter=',', skipinitialspace=True) 

beer, abv, style, brewery = set(), set(), set(), set()
for row in csvData:
    beer.add(row[10])
    abv.add(row[11])
    style.add(row[7])
    brewery.add(row[1])
print(beer, abv, style, brewery) 

出于某种原因,我收到一个错误:

Traceback (most recent call last):
  File "filter.py", line 8, in <module>
    beer.add(row[10])
IndexError: list index out of range

这是我beers.csv文件的前 15 行:

brewery_id,brewery_name,review_time,review_overall,review_aroma,review_appearance,review_profilename,beer_style,review_palate,review_taste,beer_name,beer_abv,beer_beerid
10325,Vecchio Birraio,1234817823,1.5,2,2.5,stcules,Hefeweizen,1.5,1.5,Sausa Weizen,5,47986
10325,Vecchio Birraio,1235915097,3,2.5,3,stcules,English Strong Ale,3,3,Red Moon,6.2,48213
10325,Vecchio Birraio,1235916604,3,2.5,3,stcules,Foreign / Export Stout,3,3,Black Horse Black Beer,6.5,48215
10325,Vecchio Birraio,1234725145,3,3,3.5,stcules,German Pilsener,2.5,3,Sausa Pils,5,47969
1075,Caldera Brewing Company,1293735206,4,4.5,4,johnmichaelsen,American Double / Imperial IPA,4,4.5,Cauldron DIPA,7.7,64883
1075,Caldera Brewing Company,1325524659,3,3.5,3.5,oline73,Herbed / Spiced Beer,3,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1318991115,3.5,3.5,3.5,Reidrover,Herbed / Spiced Beer,4,4,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1306276018,3,2.5,3.5,alpinebryant,Herbed / Spiced Beer,2,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1290454503,4,3,3.5,LordAdmNelson,Herbed / Spiced Beer,3.5,4,Caldera Ginger Beer,4.7,52159

我究竟做错了什么?

4

1 回答 1

2
import csv

cols = ('brewery_name', 'beer_style', 'beer_name', 'beer_abv')
sets = {}
with open("beers.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        for col in cols:
            sets.setdefault(col, set()).add(row[col])
print(sets)

$ python3 beers.py {'brewery_name': {'Caldera Brewing Company', 'Vecchio Birraio'}, 'beer_style': {'American Double / Imperial IPA', 'Foreign / Export Stout', 'Herbed / Spiced Beer', 'German Pilsener', 'Hefeweizen', 'English Strong Ale'}, 'beer_name': {'Black Horse Black Beer', 'Sausa Pils', 'Sausa Weizen', 'Cauldron DIPA', 'Caldera Ginger Beer', '红月亮'}, 'beer_abv': {'5', '7.7', '4.7', '6.5', '6.2'}}

于 2020-02-18T02:01:57.687 回答