簡體   English   中英

如何用python把txt文件轉成json格式?

[英]How to convert txt file to json format with python?

我正在嘗試編寫一個腳本,該腳本接受一個文本文件並將其轉換為 json 文件:

有問題的文本文件具有以下內容:

Mango
800 lbs
Mango contains higher levels of vitamin C than ordinary fruits. Eating mango can also reduce cholesterol and triglycerides,and help prevent cardiovascular disease. Due to its high level of vitamins, regular consumption of mango play an important role in improving body function and moisturizing the skin.

json 文件必須具有以下格式

{"name": "Mango", "weight": 800, "description": "Mango contains higher levels of vitamin C than ordinary fruits. Eating mango can also reduce cholesterol and triglycerides,and help prevent cardiovascular disease. Due to its high level of vitamins, regular consumption of mango play an important role in improving body function and moisturizing the skin.", "image_name": "010.jpeg"}

這是我的代碼:

import json

# the file to be converted to
# json format
filename = 'descriptions.txt'

fields = ["name", "weight", "descriptions"]

# dictionary where the lines from
# text will be stored
dict1 = {}

# creating dictionary
with open(filename) as fh:
    i = 0

    for line in fh:

        # reads each line and trims of extra the spaces
        # and gives only the valid words

        description = line.strip().split(None, 1)

        print(description)

        while i < len(fields):
            dict1[fields[i]] = description[i]
            i += 1

out_file = open("test1.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)
out_file.close()

當我運行代碼時,我收到錯誤消息“IndexError:列表索引超出范圍”。

另一個規范是重量字段必須只顯示數字 800 而沒有“lbs”部分

有人可以告訴我我做錯了什么嗎?

最好的祝福

尼古拉斯·蒙泰羅·維塔爾

嘗試像這樣填充你的字典:

dict1 = {}
fields = ["name", "weight", "descriptions"]
with open("File_new.txt") as fh:
    # you can iterate over a fields and the file's lines at the same time using zip 
    for field, line in zip(fields, fh):
        dict1[field] = line.strip() if field != "weight" else line.strip().split()[0]
print(dict1)

您在開始 for 循環之前初始化i = 0 ,但您永遠不會在循環內將其重置回 0。 無論如何,while 循環的邏輯都是錯誤的。 完全放棄該循環會更容易:

import json
filename = 'descriptions.txt'
fields = ["name", "weight", "descriptions"]
dict1 = {}
with open(filename) as fh:
    lines = fh.readlines()
    for i, f in enumerate(fields):
        dict1[f] = lines[i].strip()
    dict1['weight'] = dict1['weight'].split()[0] 

with open("test1.json", "w") as out_file:
   json.dump(dict1, out_file, indent = 4, sort_keys = False)

暫無
暫無

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

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