python parse specific text in multiple line

2019-08-18 06:09发布

问题:

I have a text file contain a sample data like this:

[|] Name: Foo Bar
[|] Username: xx@example.org
[|] NickName: Boox AA
[|] Logo Box: Unique-w.jpg
[|] Country: EU
=========================================
[|] Name: Doo Mar
[|] Username: cc@example.net
[|] Logo Box: Unique-w.jpg
[|] Country: EU
[|] Mob: 00000000

I need to get Username and Logo Box values

I tried using for loop to get 2 lines each time and analyze it but it does not work as expected.

def read_file_lines(file_path):
    with open(file_path) as fp:
        return fp.readlines()


lines = read_file_lines('data.txt')

result = {}
index = 1
for line in lines:
    if 'Username:' in line:
        result[index] = {}
        result[index]['username'] = line # cleanup
    elif 'Logo Box:' in line:
        result[index]['LogoBox'] = line  # cleanup
    index += 1

example valid solution output would be:

result = {
'1': {'username': 'xx@example.org', 'LogoBox': 'Unique-w.jpg'}
}

I appreciate your help

回答1:

try this code below:

with open('myfile.txt', 'r') as f:
    for line in f:
        if ':' in line:
            k, v = line.split(':')
            if 'Username' in k:
                print('Username:', v)
            elif 'Logo Box' in k:
                print('Logo Box:', v)

output:

Username:  xx@example.org

Logo Box:  Unique-w.jpg

Username:  cc@example.net

Logo Box:  Unique-w.jpg