繁体   English   中英

如何在Python中向上移动一行文本文件?

[英]How to move a line of text file one line up in Python?

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

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

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

您的错误之一是.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:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM