【问题标题】:Python convert dictionary to CSVPython 将字典转换为 CSV
【发布时间】:2018-12-09 18:33:21
【问题描述】:

我正在尝试将字典转换为 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

【问题讨论】:

  • 尽量不要链接到外部网站,因为随着时间的推移,这些链接可能会断开,如果您想发布数据,请直接发布而不是图片。另外,如果您可以发布字典的最终版本会更好,因为您的示例无法在没有完整代码的情况下运行。
  • 链接实际上显示了我想要获取的图像。我还不能发布图片。我是编码新手
  • 我可能会以不同的方式完成您的任务。看来您没有使用字典的功能来收集数据,因为我到处都可以看到函数。该站点返回一个易于使用的漂亮 JSON 响应。另一点是,我会使用 pandas 来完全控制我的数据。有了它,您可以将数据存储为不同的格式,例如平面文件为 CSV、noSQL(例如 MongoDB)、压缩泡菜、HD5 等。在下面发布示例编码作为另一个可能的答案。

标签: python python-3.x dictionary web-scraping export-to-csv


【解决方案1】:

使用来自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"])

【讨论】:

  • 我已经尝试过了,但是如果我从 x 更改为 'x',只会显示一个数据。所以,我已经编辑了代码,这样你就可以更好地了解我想要做什么。
  • 您能否发布data_list 的示例以便我可以修改此代码?
【解决方案2】:

我想,也许你只是想合并一些像 excel 这样的单元格吗? 如果是,我认为这在 csv 中是不可能的,因为 csv 格式不包含像 excel 这样的单元格样式信息。 一些可能的解决方案:

  1. 使用openpyxl生成excel文件而不是csv,然后可以通过“worksheet.merge_cells()”函数合并单元格。
  2. 不要尝试合并单元格,只保留每一行的标题、价格等字段,数据格式应该是这样的:

    第一行:{'title':'test_title', 'price': 22, 'image': 'image_link_1'}

    第二行:{'title':'test_title', 'price': 22, 'image': 'image_link_2'}

  3. 不要尝试合并单元格,而是将标题、价格和其他字段设置为空白字符串,这样它就不会显示在您的 csv 文件中。

  4. 使用换行符控制格式,将多行同标题合并为一行。

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    如果我是你,我会做这件事有点不同。我不喜欢你调用这么多函数,而这个网站提供了一个漂亮的 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)
    

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2017-11-08
      • 2017-09-13
      • 2018-08-13
      • 2021-12-22
      • 2021-04-01
      相关资源
      最近更新 更多