簡體   English   中英

將列表字典寫入 CSV 文件

[英]Write to dictionary of lists to a CSV file

我希望在垂直顯示時關聯多個值。 當我將字典的 value 鍵寫入 writerows (w.writerows(d.values()) 時,它是水平的,而我想要它是垂直的。

from bs4 import BeautifulSoup
import csv
r = requests.get('https://www.ufc.com/rankings')
s = BeautifulSoup(r.text, 'lxml')
fighters = s.find_all('div','view-grouping')
name = []
weightdivisions = []
for x in fighters:
    z = [names.string for names in x.find_all('a')]
    name.append(z)
    divisions = x.find('h4')
    dd = divisions.text
    weightdivisions.append(dd)

d = dict(zip(weightdivisions,name))
print(d)
with open('ufc.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(d.values())

嘗試:

import csv
from bs4 import BeautifulSoup


r = requests.get("https://www.ufc.com/rankings")
s = BeautifulSoup(r.text, "lxml")
fighters = s.find_all("div", "view-grouping")
name = []
weightdivisions = []
for x in fighters:
    z = [names.string for names in x.find_all("a")]
    name.append(z)
    divisions = x.find("h4")
    dd = divisions.text
    weightdivisions.append(dd)

d = dict(zip(weightdivisions, name))
with open("ufc.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(d.keys())

    for column in d:
        d[column] = iter(d[column])

    while True:
        row = [next(d[column], "") for column in d]
        if all(val == "" for val in row):
            break
        w.writerow(row)

這會正確保存ufc.csv (來自 LibreOffice 的屏幕截圖):

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM