简体   繁体   中英

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

I have a text file containing some Parameters and their values. After parsing it in python a Dictionary is created. Text file is something similar to:

Object1
 House: Blue
 Car: Red
Green
 Garden: Big

Object2
 House: Beatiful
 Car: Nice
 Garden: Small

After the Dictionary is created i also create some blocks which then help me to parse everything in json file. The Problem is that the "Green" is not detected as a value to car but as a new object. Therefore what I would like to do is to move the "Green" string one line up and to have a text file like this.

Object1
 House: Blue
 Car: Red Green
 Garden: Big

Object2
 House: Beatiful
 Car: Nice
 Garden: Small

How can I do this in Python? I was thinking of using regex functions to find the green but still I don't know how to put it one line up.

Piece of Code:

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

Question : I was thinking of using regex functions to find the green but still i dont know how to put it one line up.

One of your mistakes are .match(line[0]) .
You match against the first character in line . This is not what you want, change to .match(line)

This results in the following Output:

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

Your header = re.compile('[a-zA-Z0-9]') matches also the Green .
How can you distingish between 'Green' and header?

Your inner = re.compile("[\\t]") matches nothing.
I suggest, change from elif inner.match(line): to else:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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