Python 将字典转换为 CSV
Python convert dictionary to CSV
我正在尝试将字典转换为 CSV 以便它可读(在它们各自的键中)。
import csv
import json
from urllib.request import urlopen
x =0
id_num = [848649491, 883560475, 431495539, 883481767, 851341658, 42842466, 173114302, 900616370, 1042383097, 859872672]
for bilangan in id_num:
with urlopen("https://shopee.com.my/api/v2/item/get?itemid="+str(bilangan)+"&shopid=1883827")as response:
source = response.read()
data = json.loads(source)
#print(json.dumps(data, indent=2))
data_list ={ x:{'title':productName(),'price':price(),'description':description(),'preorder':checkPreorder(),
'estimate delivery':estimateDelivery(),'variation': variation(), 'category':categories(),
'brand':brand(),'image':image_link()}}
#print(data_list[x])
x =+ 1
我将数据存储在 x
中,因此它将从 0 循环到 1、2 等等。我已经尝试了很多东西,但仍然找不到使它看起来像这样或接近这样的方法这个:
https://i.stack.imgur.com/WoOpe.jpg
使用 csv
模块中的 DictWriter
演示:
import csv
data_list ={'x':{'title':'productName()','price':'price()','description':'description()','preorder':'checkPreorder()',
'estimate delivery':'estimateDelivery()','variation': 'variation()', 'category':'categories()',
'brand':'brand()','image':'image_link()'}}
with open(filename, "w") as infile:
writer = csv.DictWriter(infile, fieldnames=data_list["x"].keys())
writer.writeheader()
writer.writerow(data_list["x"])
我想,也许您只是想像 excel 那样合并一些单元格呢?
如果是,我认为这在csv中是不可能的,因为csv格式不包含像excel这样的单元格样式信息。
一些可能的解决方案:
- 使用 openpyxl 生成 excel 文件而不是 csv,然后您可以使用 "worksheet.merge_cells()" 函数合并单元格。
不要尝试合并单元格,只保留每行的标题、价格和其他字段,数据格式应为:
第一行:{'title':'test_title','price':22,'image':'image_link_1'}
第二行:{'title':'test_title','price':22,'image':'image_link_2'}
不要尝试合并单元格,而是将标题、价格和其他字段设置为空字符串,这样它就不会显示在您的csv文件中。
- 使用换行符控制格式,将相同标题的多行合并为一行。
希望对您有所帮助。
如果我是你,我的做法会有所不同。我不喜欢你调用这么多函数,而这个网站提供了一个漂亮的 JSON 响应 :) 此外,我将使用 pandas 库,这样我就可以完全控制我的数据。我不是 CSV 爱好者。这是一个愚蠢的原型:
import requests
import pandas as pd
# Create our dictionary with our items lists
data_list = {'title':[],'price':[],'description':[],'preorder':[],
'estimate delivery':[],'variation': [], 'categories':[],
'brand':[],'image':[]}
# API url
url ='https://shopee.com.my/api/v2/item/get'
id_nums = [848649491, 883560475, 431495539, 883481767, 851341658,
42842466, 173114302, 900616370, 1042383097, 859872672]
shop_id = 1883827
# Loop throw id_nums and return the goodies
for id_num in id_nums:
params = {
'itemid': id_num, # take values from id_nums
'shopid':shop_id}
r = requests.get(url, params=params)
# Check if we got something :)
if r.ok:
data_json = r.json()
# This web site returns a beautiful JSON we can slice :)
product = data_json['item']
# Lets populate our data_list with the items we got. We could simply
# creating one function to do this, but for now this will do
data_list['title'].append(product['name'])
data_list['price'].append(product['price'])
data_list['description'].append(product['description'])
data_list['preorder'].append(product['is_pre_order'])
data_list['estimate delivery'].append(product['estimated_days'])
data_list['variation'].append(product['tier_variations'])
data_list['categories'].append([product['categories'][i]['display_name'] for i, _ in enumerate(product['categories'])])
data_list['brand'].append(product['brand'])
data_list['image'].append(product['image'])
else:
# Do something if we hit connection error or something.
# may be retry or ignore
pass
# Putting dictionary to a list and ordering :)
df = pd.DataFrame(data_list)
df = df[['title','price','description','preorder','estimate delivery',
'variation', 'categories','brand','image']]
# df.to ...? There are dozen of different ways to store your data
# that are far better than CSV, e.g. MongoDB, HD5 or compressed pickle
df.to_csv('my_data.csv', sep = ';', encoding='utf-8', index=False)
我正在尝试将字典转换为 CSV 以便它可读(在它们各自的键中)。
import csv
import json
from urllib.request import urlopen
x =0
id_num = [848649491, 883560475, 431495539, 883481767, 851341658, 42842466, 173114302, 900616370, 1042383097, 859872672]
for bilangan in id_num:
with urlopen("https://shopee.com.my/api/v2/item/get?itemid="+str(bilangan)+"&shopid=1883827")as response:
source = response.read()
data = json.loads(source)
#print(json.dumps(data, indent=2))
data_list ={ x:{'title':productName(),'price':price(),'description':description(),'preorder':checkPreorder(),
'estimate delivery':estimateDelivery(),'variation': variation(), 'category':categories(),
'brand':brand(),'image':image_link()}}
#print(data_list[x])
x =+ 1
我将数据存储在 x
中,因此它将从 0 循环到 1、2 等等。我已经尝试了很多东西,但仍然找不到使它看起来像这样或接近这样的方法这个:
https://i.stack.imgur.com/WoOpe.jpg
使用 csv
模块中的 DictWriter
演示:
import csv
data_list ={'x':{'title':'productName()','price':'price()','description':'description()','preorder':'checkPreorder()',
'estimate delivery':'estimateDelivery()','variation': 'variation()', 'category':'categories()',
'brand':'brand()','image':'image_link()'}}
with open(filename, "w") as infile:
writer = csv.DictWriter(infile, fieldnames=data_list["x"].keys())
writer.writeheader()
writer.writerow(data_list["x"])
我想,也许您只是想像 excel 那样合并一些单元格呢? 如果是,我认为这在csv中是不可能的,因为csv格式不包含像excel这样的单元格样式信息。 一些可能的解决方案:
- 使用 openpyxl 生成 excel 文件而不是 csv,然后您可以使用 "worksheet.merge_cells()" 函数合并单元格。
不要尝试合并单元格,只保留每行的标题、价格和其他字段,数据格式应为:
第一行:{'title':'test_title','price':22,'image':'image_link_1'}
第二行:{'title':'test_title','price':22,'image':'image_link_2'}
不要尝试合并单元格,而是将标题、价格和其他字段设置为空字符串,这样它就不会显示在您的csv文件中。
- 使用换行符控制格式,将相同标题的多行合并为一行。
希望对您有所帮助。
如果我是你,我的做法会有所不同。我不喜欢你调用这么多函数,而这个网站提供了一个漂亮的 JSON 响应 :) 此外,我将使用 pandas 库,这样我就可以完全控制我的数据。我不是 CSV 爱好者。这是一个愚蠢的原型:
import requests
import pandas as pd
# Create our dictionary with our items lists
data_list = {'title':[],'price':[],'description':[],'preorder':[],
'estimate delivery':[],'variation': [], 'categories':[],
'brand':[],'image':[]}
# API url
url ='https://shopee.com.my/api/v2/item/get'
id_nums = [848649491, 883560475, 431495539, 883481767, 851341658,
42842466, 173114302, 900616370, 1042383097, 859872672]
shop_id = 1883827
# Loop throw id_nums and return the goodies
for id_num in id_nums:
params = {
'itemid': id_num, # take values from id_nums
'shopid':shop_id}
r = requests.get(url, params=params)
# Check if we got something :)
if r.ok:
data_json = r.json()
# This web site returns a beautiful JSON we can slice :)
product = data_json['item']
# Lets populate our data_list with the items we got. We could simply
# creating one function to do this, but for now this will do
data_list['title'].append(product['name'])
data_list['price'].append(product['price'])
data_list['description'].append(product['description'])
data_list['preorder'].append(product['is_pre_order'])
data_list['estimate delivery'].append(product['estimated_days'])
data_list['variation'].append(product['tier_variations'])
data_list['categories'].append([product['categories'][i]['display_name'] for i, _ in enumerate(product['categories'])])
data_list['brand'].append(product['brand'])
data_list['image'].append(product['image'])
else:
# Do something if we hit connection error or something.
# may be retry or ignore
pass
# Putting dictionary to a list and ordering :)
df = pd.DataFrame(data_list)
df = df[['title','price','description','preorder','estimate delivery',
'variation', 'categories','brand','image']]
# df.to ...? There are dozen of different ways to store your data
# that are far better than CSV, e.g. MongoDB, HD5 or compressed pickle
df.to_csv('my_data.csv', sep = ';', encoding='utf-8', index=False)