[英]Issue Python writing - reading CSV of a dictionary
我在Python(最新版本)中的字典有问题。 这是我的字典: [ {dict1} , {dict2} , ... ]
所有字典都类似于:
{'Date': '2016-10-17',
'Message_body': ' Version française BUSINESS EVENTS - SPRING 2016 April 5: YESS EVENT ON SCALING UP Robin Bonsey, Hystra Consultant, will discuss business solutions to the predicament of small holder farmer',
'Sender': 'xxxxxxxxxxx@gmail.com',
'Subject': 'Fwd: Inclusive business events - spring 2016'}
。
根据Python,每个值( type(dict1['Message_body'])
)的'type'是“ str”。 我的问题是将此字典词典转换为CSV文件(使用键'Date' , 'Message_body' , 'Sender', 'Subject'
)。 这是我的代码:
def export_dict_list_to_csv(data, filename):
with open(filename, 'w',encoding='utf-8',newline='') as f:
# Assuming that all dictionaries in the list have the same keys.
headers = sorted([k for k, v in data[0].items()])
csv_data = [headers]
for d in data:
csv_data.append([d[h] for h in headers])
writer = csv.writer(f)
writer.writerows(csv_data)
export_dict_list_to_csv(final_list, 'chili.csv')
它工作得很好,但是错别字很奇怪。 例如,在.csv中,我使用的是“ Paque dans lesPensées的Chaque moi voudraitÃ?tre le tyran de tous lesPensées”,而不是“ Pascal dans lesPensées”是“ Chaque moi voudraitêtrele tyran de tous les autres” 。 在“ str”形式中,我有“良好的错字”,但在.csv中,它不是良好的错字(我不知道为什么)。 如果CSV文件的“读取”恢复了“ str”的良好初始输入错误,则此问题并不是很重要。
但是我无法正确读取创建的CSV ...我试过了:
with open('chili.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
print (row)
我收到错误消息“ UnicodeDecodeError:'ascii'编解码器无法解码位置1087的字节0xc3:序数不在范围(128)中”
我尝试了:
with open('/Users/Marco/HandB/Gmail/chili.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
print (row)
错误:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)
因此,我有两个问题:1)编写CSV文件的方式是否不错? 为什么我的CSV上有错字?
2)如何读取之前创建的CSV? 我在互联网上搜索了几个小时,但没有发现什么特别的东西可以帮助我解决这个问题。 特别是,我不太了解围绕“编码”问题的所有问题,我只知道dict中的值是str类型,我认为它们是UTF-8格式。 这是代码:(我清除了从GMAIL API收到的“数据”)
mssg_parts = payld['parts'] # fetching the message parts
part_one = mssg_parts[0] # fetching first element of the part
part_body = part_one['body'] # fetching body of the message
part_data = part_body['data'] # fetching data from the body
clean_one = part_data.replace("-","+") # decoding from Base64 to UTF-8
clean_one = clean_one.replace("_","/") # decoding from Base64 to UTF-8
clean_two = base64.b64decode (bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8
soup = BeautifulSoup(clean_two , "lxml" )
soup = BeautifulSoup(clean_two, "html")
soup.get_text()
mssg_body = soup.body()
# mssg_body is a readible form of message body
# depending on the end user's requirements, it can be further cleaned
# using regex, beautiful soup, or any other method
temp_dict['Message_body'] = mssg_body
我写下了为我提供“ Message_body”部分的代码,因为它可以帮助您了解消息的格式以及将其转换为CSV文件的方式。
在此先多谢! :)
看来您使用的是python3。 您将要以文本模式而不是二进制模式打开文件。 此外,如果您的数据包含一些特殊字符,请在调用open
打开文件以进行读取时设置编码。 这可以通过encoding=...
:
with open('/Users/Marco/HandB/Gmail/chili.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
...
如果您想以字典形式阅读csv,则可能应该考虑看看csv.DictReader
该文档提供了一些方便的示例来帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.