[英]How to convert a JSON list into two different columns in a CSV file?
[英]How to export a list into different columns of a csv file?
我試圖找出如何將以下列表導出到.csv文件,匹配某些列。
[{'amount': '100', 'unit': 'g.', 'ingredient': 'mælkechokolade'}, {'amount': '20', 'unit': 'g.', 'ingredient': 'mini marshmallows'}, {'amount': '40', 'unit': 'g.', 'ingredient': 'saltede peanuts'}]
以上是解析字符串並使用正則表達式將內容與其正確的標頭匹配的結果。
r = re.compile(r"(?P<amount>\\d+)\\s+(?P<unit>\\w+.)\\s+(?P<ingredient>.+?(?=<))") print([m.groupdict() for m in r.finditer(s)])
有沒有辦法使用.writerow正確導出該列表? 到目前為止我無法使它工作。
您可以使用pandas.to_csv
獲取數據結構並將其寫入csv:
import pandas as pd
somedata = [{'amount': '100', 'unit': 'g.', 'ingredient': 'mælkechokolade'}, {'amount': '20', 'unit': 'g.', 'ingredient': 'mini marshmallows'}, {'amount': '40', 'unit': 'g.', 'ingredient': 'saltede peanuts'}]
df = pd.DataFrame(somedata)
with open("somefile.csv", 'w') as fh:
df.to_csv(fh)
雖然pandas
需要安裝pip install pandas
( pip install pandas
)。 否則你可以使用內置的csv
模塊:
import csv
somedata = [{'amount': '100', 'unit': 'g.', 'ingredient': 'mælkechokolade'}, {'amount': '20', 'unit': 'g.', 'ingredient': 'mini marshmallows'}, {'amount': '40', 'unit': 'g.', 'ingredient': 'saltede peanuts'}]
# This will keep order consistent
headers = [k for k in somedata[0].keys())
new_data = [[rec.get(header) for header in headers] for rec in somedata]
with open('somefile.csv', 'w') as fh:
writer = csv.writer(fh, delimiter=',')
writer.writerow(headers)
for row in new_data:
writer.writerow(row)
這將導致
amount,unit,ingredient
100,g.,mælkechokolade
20,g.,mini marshmallows
40,g.,saltede peanuts
您可以使用pandas DataFrame的to_csv函數
import pandas as pd
d = [{'amount': '100', 'unit': 'g.', 'ingredient': 'mælkechokolade'}, {'amount': '20', 'unit': 'g.', 'ingredient': 'mini marshmallows'}, {'amount': '40', 'unit': 'g.', 'ingredient': 'saltede peanuts'}]
pd.DataFrame(d).to_csv('ala.csv')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.