简体   繁体   English

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

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

i am trying to write a script that takes a text file and converts it into a json file:我正在尝试编写一个脚本,该脚本接受一个文本文件并将其转换为 json 文件:

the text file in question has the following contents:有问题的文本文件具有以下内容:

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.

the json file must have the following format 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"}

here is my code:这是我的代码:

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()

when i run the code, i am getting the error message "IndexError: list index out of range".当我运行代码时,我收到错误消息“IndexError:列表索引超出范围”。

Another specification is that the weight field must only display the number 800 without the "lbs" part另一个规范是重量字段必须只显示数字 800 而没有“lbs”部分

Can someone please tell me what i did wrong?有人可以告诉我我做错了什么吗?

best regards最好的祝福

Nicholas Monteiro Vital尼古拉斯·蒙泰罗·维塔尔

Try to populate your dict like this:尝试像这样填充你的字典:

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)

You initialize i = 0 before starting the for loop, but you never reset it back to 0 inside the loop.您在开始 for 循环之前初始化i = 0 ,但您永远不会在循环内将其重置回 0。 And anyway, logic of the while loop is all wrong.无论如何,while 循环的逻辑都是错误的。 It would be easier to drop that loop altogether:完全放弃该循环会更容易:

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