首页 > 解决方案 > 如何在Python中将一行文本文件向上移动一行?

问题描述

我有一个包含一些参数及其值的文本文件。在 python 中解析它之后,创建了一个字典。文本文件类似于:

Object1
 House: Blue
 Car: Red
Green
 Garden: Big

Object2
 House: Beatiful
 Car: Nice
 Garden: Small

创建字典后,我还创建了一些块,然后帮助我解析 json 文件中的所有内容。问题是“绿色”没有被检测为汽车的值,而是作为一个新对象。因此,我想做的是将“绿色”字符串移动一行并拥有一个像这样的文本文件。

Object1
 House: Blue
 Car: Red Green
 Garden: Big

Object2
 House: Beatiful
 Car: Nice
 Garden: Small

我怎样才能在 Python 中做到这一点?我正在考虑使用正则表达式函数来查找绿色,但我仍然不知道如何将它排成一行。

一段代码:

to_json = {}
answer = {}
block_cnt = 1
header = re.compile('[a-zA-Z0-9]')
inner = re.compile("[\t]")
empty = re.compile("[\n]",)
with open(output, 'r') as document:
    for line in document:
        #print line

        if empty.match(line[0]):
            continue

        elif header.match(line[0]):
            if answer:
                to_json[block_cnt] = answer
                #print answer
                block_cnt += 1
                answer = {}
        elif inner.match(line[0]):
            _key, value = line.split(":  ")
            tab, key = _key.split("\t")
            answer[key] = value.strip("\n")   

标签: pythondictionarytext-filesline

解决方案


问题:我正在考虑使用正则表达式函数来查找绿色,但我仍然不知道如何将它排成一行。

你的错误之一是.match(line[0])
您匹配 中的第一个字符line。这不是你想要的,改为.match(line)

这将产生以下输出:

header:Object1   
header:Green
empty:
header:Object2
{}

你的header = re.compile('[a-zA-Z0-9]')比赛也是Green.
您如何区分“绿色”和标题?

你的inner = re.compile("[\t]")匹配没有。
我建议,从更改elif inner.match(line):else:


推荐阅读