簡體   English   中英

試圖在Python中編寫一個字典列表到csv,遇到編碼問題

[英]Trying to write a list of dictionaries to csv in Python, running into encoding issues

所以我遇到了一個編碼問題,源於在Python中將字典寫入csv。

這是一個示例代碼:

import csv

some_list = ['jalape\xc3\xb1o']

with open('test_encode_output.csv', 'wb') as csvfile:
    output_file = csv.writer(csvfile)
    for item in some_list:
        output_file.writerow([item])

這工作得很好,並給了我一個寫有“jalapeño”的csv文件。

但是,當我創建一個包含這樣的UTF-8字符的字典列表時......

import csv

some_list = [{'main': ['4 dried ancho chile peppers, stems, veins
            and seeds removed']}, {'main': ['2 jalape\xc3\xb1o 
            peppers, seeded and chopped', '1 dash salt']}]

with open('test_encode_output.csv', 'wb') as csvfile:
    output_file = csv.writer(csvfile)
    for item in some_list:
        output_file.writerow([item])

我只是獲得一個包含2行的csv文件,其中包含以下條目:

{'main': ['4 dried ancho chile peppers, stems, veins and seeds removed']}
{'main': ['2 jalape\xc3\xb1o peppers, seeded and chopped', '1 dash salt']}

我知道我的東西是用正確的編碼寫的,但因為它們不是字符串,當它們被csv.writer寫出時,它們就是按原樣編寫的。 這令人沮喪。 我在這里搜索了一些類似的問題,人們已經提到過使用csv.DictWriter,但這對我來說效果不好,因為我的詞典列表並不只是一鍵'main' 有些人還有其他鑰匙,比如'toppings''crust'等。不僅如此,我還在做更多的工作,最終的輸出是按照數量,單位,成分格式化成分,所以我最終會有一個字典列表

[{'main': {'amount': ['4'], 'unit': [''], 
'ingredient': ['dried ancho chile peppers']}},
{'topping': {'amount': ['1'], 'unit': ['pump'], 
'ingredient': ['cool whip']}, 'filling': 
{'amount': ['2'], 'unit': ['cups'], 
'ingredient': ['strawberry jam']}}]

說真的,任何幫助都會非常感激,否則我必須在LibreOffice中使用find和replace來修復所有那些\\ x ** UTF-8編碼。

謝謝!

您正在將字典寫入CSV文件,而.writerow()期望列表具有在寫入時變為字符串的奇異值。

不要寫字典,這些都會變成字符串表示,正如您所發現的那樣。

您需要確定如何將每個字典的鍵和/或值轉換為列,其中每列是單個原始值。

例如,如果您只想編寫main鍵(如果存在),則執行以下操作:

with open('test_encode_output.csv', 'wb') as csvfile:
    output_file = csv.writer(csvfile)
    for item in some_list:
        if 'main' in item:
            output_file.writerow(item['main'])

假設與'main'鍵相關聯的值始終是值列表。

如果您想使用Unicode值保留字典,那么您使用的是錯誤的工具。 CSV是一種平面數據格式,只是行和原始列。 使用可以保留適量信息的工具。

對於包含字符串鍵,列表,數字和unicode文本的字典,您可以使用JSON,或者如果涉及更復雜和自定義的數據類型,您可以使用pickle 使用JSON時,您確實希望從字節字符串解碼為Python Unicode值,或者始終使用UTF-8編碼的字節字符串,或者說明json應如何使用encoding關鍵字為您處理字符串編碼:

import json

with open('data.json', 'w') as jsonfile:
    json.dump(some_list, jsonfile, encoding='utf8')

因為JSON字符串始終是unicode值。 encoding的默認值是utf8但為了清楚起見,我在這里添加了它。

再次加載數據:

with open('data.json', 'r') as jsonfile:
    some_list = json.load(jsonfile)

請注意,這返回unicode字符串, 而不是編碼為UTF8的字符串。

pickle模塊的工作方式大致相同,但數據格式不是人類可讀的:

import pickle

# store
with open('data.pickle', 'wb') as pfile:
    pickle.dump(some_list, pfile)

# load
with open('data.pickle', 'rb') as pfile:
    some_list = pickle.load(pfile)

pickle完全按照您存儲的方式返回您的數據。 字節字符串保持字節字符串,unicode值將作為unicode恢復。

正如您在輸出中看到的那樣,您已經使用了字典,因此如果您希望處理該字符串,則必須編寫以下內容:

import csv

some_list = [{'main': ['4 dried ancho chile peppers, stems, veins', '\xc2\xa0\xc2\xa0\xc2\xa0 and seeds removed']}, {'main': ['2 jalape\xc3\xb1o peppers, seeded and chopped', '1 dash salt']}]

with open('test_encode_output.csv', 'wb') as csvfile:
    output_file = csv.writer(csvfile)
    for item in some_list:
        output_file.writerow(item['main'])  #so instead of [item], we use item['main']

我知道這可能不是你想要的代碼,因為它限制你調用每個鍵主,但至少現在處理它。

你可能想要更好地制定你想做的事情,因為現在還不是很清楚(至少對我而言)。 例如,你想要一個csv文件,它在第一個單元格中給你main,然后4個干...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM