![](/img/trans.png)
[英]Python script to Grep strings from input file and output in csv format
[英]python , output from csv format to json from
我有csv fromat中的代碼輸出,我試圖將其轉換為json但它在json文件中轉換為一些錯誤。 這是csv代碼。 如果你告訴我如何使用正確的輸出json格式將輸出轉換為json而不是csv,我將感激不盡。
謝謝
print >> out, 'text '
rows = zip(texts)
from csv import writer
csv = writer(out)
for row in rows:
values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
out.close()
Json應該定義數據結構。 我使用以下結構作為示例:
[{"title" : "Gone with the wind", "description" : "A book"},
{"title" : "White Fang", "description" : "A book"},
{"title" : "Dracula", "description" : "A book"},
{"title" : "Van Helsing", "description" : "A movie"},
...]
以下是將其轉換為json數組對象並寫入文件的代碼:
# I'm not sure what you are doing here, but zip returns a list of tuples
# For example: [("Gone with the wind", "A book"), ("Van Helsing", "A movie")...]
rows = zip(texts)
with open(filename, 'w') as f:
data = list()
for title, desc in rows: # According to your tuple
data.append(dict(title=title, description=desc))
json.dump(data, f) # Write the list into the output file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.