如何在Python中解析文本文件并转换为JSON

时间:2015-07-18 19:44:27

标签: python json scripting

我有一个大文件格式如下:

MainActivityFragment

......这重复了一段时间。我试图将其转换为JSON,因此每个块都是这样的:

"string in quotes"
string
string
string
number
|-

这是我到目前为止所做的:

"name": "string in quotes"
"description": "string"
"info": "string"
"author": "string"
"year": number

认为我可以做一些类似于行号模数的东西,但是我不确定这是否是正确的方法。

3 个答案:

答案 0 :(得分:1)

我认为这样做会有所帮助。

import itertools
import json

with open('unformatted.txt', 'r') as f_in, open('formatted.json', 'w') as f_out:
    for name, desc, info, author, yr, ignore in itertools.izip_longest(*[f_in]*6):
        record = {
            "name": '"' + name.strip() + '"',
            "description": desc.strip(),
            "info": info.strip(),
            "author": author.strip(),
            "year": int(yr.strip()),
        }
        f_out.write(json.dumps(record))

答案 1 :(得分:1)

您可以使用itertools.groupby将所有部分分组,然后将json.dump字符串分组到您的json文件中:

from itertools import groupby
import json
names = ["name", "description","info","author", "year"]

with open("test.csv") as f, open("out.json","w") as out:
    grouped = groupby(map(str.rstrip,f), key=lambda x: x.startswith("|-"))
    for k,v in grouped:
        if not k:
            json.dump(dict(zip(names,v)),out)
            out.write("\n")

输入:

"string in quotes"
string
string
string
number
|-
"other string in quotes"
string2
string2
string2
number2

输出:

{"author": "string", "name": "\"string in quotes\"", "description": "string", "info": "string", "year": "number"}
{"author": "string2", "name": "\"other string in quotes\"", "description": "string2", "info": "string2", "year": "number2"}

要访问只是遍历文件并加载:

In [6]: with open("out.json") as out:
            for line in out:
                 print(json.loads(line))
   ...:         
{'name': '"string in quotes"', 'info': 'string', 'author': 'string', 'year': 'number', 'description': 'string'}
{'name': '"other string in quotes"', 'info': 'string2', 'author': 'string2', 'year': 'number2', 'description': 'string2'}

答案 2 :(得分:1)

这是做基本工作的一个粗略的例子。

它使用生成器将输入分成第一批(第6个),另一个用于将键添加到值中。

import json


def read():
    with open('input.txt', 'r') as f:
        return [l.strip() for l in f.readlines()]


def batch(content, n=1):
    length = len(content)
    for num_idx in range(0, length, n):
        yield content[num_idx:min(num_idx+n, length)]


def emit(batched):
    for n, name in enumerate([
        'name', 'description', 'info', 'author', 'year'
    ]):
        yield name, batched[n]

content = read()
batched = batch(content, 6)
res = [dict(emit(b)) for b in batched]

print(res)

with open('output.json', 'w') as f:
    f.write(json.dumps(res, indent=4))

更新

使用此方法,您可以轻松挂钩格式化功能,以便 名称 值正确无误

像这样扩展emit函数:

def emit(batched):
    def _quotes(q):
        return q.replace('"', '')

    def _pass(p):
        return p

    def _num(n):
        try:
            return int(n)
        except ValueError:
            return n

    for n, (name, func) in enumerate([
        ('name', _quotes),
        ('description', _pass),
        ('info', _pass),
        ('author', _pass),
        ('year', _num)
    ]):
        yield name, func(batched[n])