【发布时间】: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