繁体   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