python parse specific text in multiple line

旧时模样 提交于 2019-12-24 19:55:58

问题


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


来源:https://stackoverflow.com/questions/55802360/python-parse-specific-text-in-multiple-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!