2

以下のコードに問題があります。

import urllib2
import csv
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://www.ny.com/clubs/nightclubs/index.html').read())
clubs = []
trains = ["A","C","E","1","2","3","4","5","6","7","N","Q","R","L","B","D","F"]
for club in soup.find_all("dt"):
    clubD = {}
    clubD["name"] = club.b.get_text()
    clubD["address"] = club.i.get_text()
    text = club.dd.get_text()
    nIndex = text.find("(")
    if(text[nIndex+1]=="2"):
        clubD["number"] = text[nIndex:nIndex+15]
    sIndex = text.find("Subway")
    sIndexEnd = text.find(".",sIndex)
    if(text[sIndexEnd-1] == "W" or text[sIndexEnd -1] == "E"):
        sIndexEnd2 = text.find(".",sIndexEnd+1)
        clubD["Subway"] = text[sIndex:sIndexEnd2]
    else:
        clubD["Subway"] = text[sIndex:sIndexEnd]
    try:
        cool = clubD["number"]
    except (ValueError,KeyError):
        clubD["number"] = "N/A"
    clubs.append(clubD)
keys = [u"name", u"address",u"number",u"Subway"]
f = open('club.csv', 'wb')
dict_writer = csv.DictWriter(f, keys)
dict_writer.writerow([unicode(s).encode("utf-8") for s in clubs])

ValueError: dict contains fields not in fieldnames というエラーが表示されます。これがどうしてなのか理解できません。どんな援助も素晴らしいでしょう。辞書をExcelファイルに変換しようとしています。

4

1 に答える 1

2

clubsは辞書のリストですが、各辞書には名前、住所、番号、地下鉄の 4 つのフィールドがあります。各フィールドをエンコードする必要があります。

# Instead of:
#dict_writer.writerow([unicode(s).encode("utf-8") for s in clubs])

# Do this:
for c in clubs:
    # Encode each field: name, address, ...
    for k in c.keys():
        c[k] = c[k].encode('utf-8').strip()

    # Write to file
    dict_writer.writerow(c)

アップデート

私はあなたのデータを見て、いくつかのフィールドの末尾が改行\nになっているので、コードを更新して、空白を同時にエンコードして削除しました。

于 2013-06-05T03:05:49.977 に答える