gpt4 book ai didi

python - 转动 python 字典。到 excel 表

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:41 25 4
gpt4 key购买 nike

我在使用以下代码时遇到问题。

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 文件。

最佳答案

clubs 是一个字典列表,而每个字典都有四个字段:名称、地址、号码和地铁。您需要对每个字段进行编码:

# 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 结尾,因此我更新了代码以同时编码和去除空格。

关于python - 转动 python 字典。到 excel 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com