python解析多行中的特定文本

时间:2019-04-22 23:31:13

标签: python python-3.x python-regex

我有一个文本文件,其中包含以下示例数据:

[|] 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

我需要获取UsernameLogo Box

我尝试使用for循环每次获取2行并对其进行分析,但无法正常工作。

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

有效解决方案输出示例为:

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

在下面尝试此代码:

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)

输出:

Username:  xx@example.org

Logo Box:  Unique-w.jpg

Username:  cc@example.net

Logo Box:  Unique-w.jpg