【发布时间】:2020-04-06 10:50:13
【问题描述】:
我有以下脚本,它为我提供了一个 csv 文件,其中包含文章 id、文章的 html 代码、文章的 url、文章的创建日期、文章的最后更新时间和作者文章,
我希望每个输出都显示在自己的列中(转置),而不是将所有输出放在一列中。
A. B. C.
1| item | body | url ...
2| 1234.| <html> | https://..
正如您在我的脚本中看到的,我尝试使用数据转置,但不幸的是结果是一样的。
import requests
import csv
import unicodedata
import getpass
# Set the request parameters
url = ''
# Credentials
user = ''
pwd = ''
# Path of the outputted csv file
csvfile = 'export.csv'
# This loop cycles through all pages of articles, converts the unicode
# to an integer, and writes the integers to an array
output_1 = []
output_1.append("item")
output_2 = []
output_2.append("body")
output_3 = []
output_3.append("html_url")
output_4 = []
output_4.append("created_at")
output_5 = []
output_5.append("updated_at")
output_6 = []
output_6.append("author")
while url:
response = requests.get(url, auth=(user, pwd))
data = response.json()
for article in data['articles']:
article_id = article['id']
decode_1 = int(article_id)
output_1.append(decode_1)
for article in data['articles']:
body = article['body']
decode_2 = unicodedata.normalize('NFKD', body).encode("utf-8")
output_2.append(decode_2)
for article in data['articles']:
html_url = article['html_url']
decode_3 =unicodedata.normalize('NFKD', html_url)
output_3.append(decode_3)
for article in data['articles']:
created_at = article['created_at']
decode_4 = unicodedata.normalize('NFKD', created_at)
output_4.append(decode_4)
for article in data['articles']:
updated_at = article['updated_at']
decode_5 = unicodedata.normalize('NFKD', updated_at)
output_5.append(decode_5)
for article in data['articles']:
author_id = article['author_id']
decode_6 = int(author_id)
output_6.append(decode_6)
print(data['next_page'])
url = data['next_page']
print("Number of articles:")
print(len(output_1))
# Data Transposition
#nontransposed_data = [("Article ID","Article Body","URL","Created At","Updated At","Author Id"), [output_1], [output_2], [output_3],[output_4],[output_5],[output_6]]
#transposed_data = zip(*nontransposed_data)
# Write to a csv file
with open(csvfile, 'w') as fp:
writer = csv.writer(fp, dialect='excel')
writer.writerow([output_1])
writer.writerow([output_2])
writer.writerow([output_3])
writer.writerow([output_4])
writer.writerow([output_5])
writer.writerow([output_6])
【问题讨论】:
-
在 pandas 库中使用
T属性或transpose()。然后使用to_csv()函数保存到一个新的汽车文件中。 -
你考虑过使用熊猫吗? pandas.pydata.org