python解析多行中的特定文本 [英] python parse specific text in multiple line
本文介绍了python解析多行中的特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,其中包含以下示例数据:
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
我需要获取Username
和Logo Box
值
我尝试使用for循环每次获取2行并对其进行分析,但无法正常工作.
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'}
}
感谢您的帮助
推荐答案
在下面尝试此代码:
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
这篇关于python解析多行中的特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文