【问题标题】:correctly write a dictionary into a csv python file by columns按列将字典正确写入 csv python 文件
【发布时间】:2018-02-18 06:25:39
【问题描述】:

如何正确地将字典写入 CSV 文件?我已将解析后的数据写入字典,我想通过 key -value 将数据写入 dict 中每个键的单独列中,以及其中一个键值对(确切地说是键 'ff')

我想按 5 列分组和分隔。例如:

0,4,9,14... - in the first column
1,5,10,15 /-second ...etc. 

问题是数据必须以utf-8编码保存,这样文件中的俄语字符才能正确显示。

这是我的代码示例。现在所有内容都写入单个列,我想在 CSV 中生成一种价目表。

我正在使用 Python 2.7

import requests
from bs4 import BeautifulSoup
import csv
import re
def get_html(url):
    r = requests.get(url)
    return r.text
url='http://www.autobody.ru/kuzovnoy-remont/'
html=get_html(url)
soup=BeautifulSoup(html, 'html.parser')


mydivs = soup.findAll('a',class_="banners_images")

urls=[]
for i in mydivs:
     ur=(i.get('href'))
     ur='http://www.autobody.ru'+str(ur)
     urls.append(ur)
#head =[]
#headers = soup.findAll('h1')
#head.append(headers[0].text.strip())
images=[]
heads =[]
artic=[]
atrib=[]
price=[]
for i in urls:
 html=get_html(i)
 soup=BeautifulSoup(html, 'html.parser')
 head = soup.find('h1').get_text()
 heads.append(head )

 image=[x['src'] for x in soup.findAll('img', {'class': 'detimg'})]
 image1='http://www.autobody.ru'+image[0]
 images.append(image1)

 price1 = soup.find('div', class_='price').get_text()
 price1=re.sub(r"c",r"p", price1)
 price.append(price1)
 for tr in soup.find('table', class_='tech').find_all('tr'):
    artic.append(tr.get_text())
 da={'titles': heads,'texts':price,'ff':artic,'images':images}

 with open('c:\\1\\121.csv','a') as f:
  f.write(u'\ufeff'.encode('utf8')) # writes "byte order mark" UTF-8 signature
  writer=csv.writer(f)
  for i in da:
   for rows in da[i]:
    writer.writerow([rows.encode('utf8')])

【问题讨论】:

  • 使用pandas。从字典中创建一个DataFrame 并使用编码为utf8 的to_csv 保存。
  • @TrigonaMinima 与 Python 的内置 CSV 模块相比,这有什么帮助?
  • 您的代码中存在一些不一致:字节顺序标记仅与 UTF-16 相关,但您随后尝试写入以 UTF-8 编码的数据。你首先需要弄清楚你真正需要什么编码。
  • @Sven 在这里他自己处理编码。有了熊猫就没有这种必要性了。代码将是干净的。而且,如果要进一步处理这些数据,那么 pandas 将有很大帮助。除此之外没有额外的优势。
  • @TrigonaMinima Python 的内置 csv 模块也不需要手动处理编码——只需在打开文件时设置编码。我觉得 pandas 不错,但如果没有实际用例,就不值得学习。

标签: python python-2.7 file csv dictionary


【解决方案1】:

您已经创建了一个普通的 CSV 写入器,但正在尝试将您的数据转换为字典并编写它。您可以使用字典编写器,但我认为避免尝试为此使用字典并将数据转换为正确格式的列表会更有意义。

目前您正在构建列中的所有数据,但需要以行形式编写。可以使用zip(*[col1, col2, col3]) 完成行/列交换。在进行过程中对数据进行编码也是有意义的:

import requests
from bs4 import BeautifulSoup
import csv
import re

def get_html(url):
    r = requests.get(url)
    return r.text

url = 'http://www.autobody.ru/kuzovnoy-remont/'
html = get_html(url)
soup = BeautifulSoup(html, 'html.parser')
mydivs = soup.findAll('a',class_="banners_images")
urls = []

for i in mydivs:
    ur = (i.get('href'))
    ur = 'http://www.autobody.ru' + str(ur)
    urls.append(ur)

images = []
heads = []
artic = []
atrib = []
price = []

with open('121.csv', 'wb') as f:        # Open the file in binary mode for Python 2.x
    f.write(u'\ufeff'.encode('utf8')) # writes "byte order mark" UTF-8 signature
    writer = csv.writer(f)

    for i in urls:
        html = get_html(i)
        soup = BeautifulSoup(html, 'html.parser')
        head = soup.find('h1').get_text()
        heads.append(head.encode('utf8'))

        image = [x['src'] for x in soup.findAll('img', {'class': 'detimg'})]
        image1 = 'http://www.autobody.ru'+image[0]
        images.append(image1.encode('utf8'))

        price1 = soup.find('div', class_='price').get_text()
        price1 = re.sub(r"c",r"p", price1)
        price.append(price1.encode('utf8'))

        for tr in soup.find('table', class_='tech').find_all('tr'):
            artic.append(tr.get_text().strip().encode('utf8'))

        writer.writerows(zip(*[heads, price, artic, images]))

这会给你一个输出文件开始:

CIVIC РУЧКА ПЕРЕД ДВЕРИ ЛЕВ ВНЕШН ЧЕРН,295 p,"Артикул
HDCVC96-500B-L",http://www.autobody.ru/upload/images/HDCVC96-500B-L.jpg.pagespeed.ce.JnqIICpcSq.jpg
CIVIC РУЧКА ПЕРЕД ДВЕРИ ЛЕВ ВНЕШН ЧЕРН,295 p,"Артикул
HDCVC96-500B-L",http://www.autobody.ru/upload/images/HDCVC96-500B-L.jpg.pagespeed.ce.JnqIICpcSq.jpg
AUDI A4 БАМПЕР ПЕРЕДН ГРУНТ,3882 p,"ОЕМ#
72180S04003",http://www.autobody.ru/upload/images/AI0A401-160X.jpg.pagespeed.ce.onSZWY1J15.jpg

【讨论】:

  • 非常感谢您的帮助
【解决方案2】:

你需要使用 DictWriter:

  1. 为列名创建键:

    keys = mydict.keys()
    

    或者只是手动:

    keys = ["column1", "columns2"]
    
  2. 将数据写入 CSV:

    with open(file_name, 'a', encoding="utf-8") as output_file:
    
    dict_writer = csv.DictWriter(output_file, keys, delimiter=',', lineterminator='\n')            
    dict_writer.writeheader()
    dict_writer.writerows([mydict])
    

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 2014-06-30
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多