亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

開啟python字典。到Excel工作表

開啟python字典。到Excel工作表

素胚勾勒不出你 2021-03-19 09:14:31
我的以下代碼有問題。import urllib2import csvfrom bs4 import BeautifulSoupsoup = 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包含不在字段名稱中的字段。我不明白這怎么可能。任何幫助將是巨大的。我正在嘗試將字典轉換為Excel文件。
查看完整描述

1 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

clubs是詞典列表,而每個詞典都有四個字段:名稱,地址,編號和Subway。您將需要對每個字段進行編碼:


# 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,因此我更新了代碼以同時編碼和去除空格。


查看完整回答
反對 回復 2021-03-30
  • 1 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號