【发布时间】:2019-09-21 16:34:00
【问题描述】:
我使用 python 逐行读取文件并根据单词“-U-:Sent”的出现将其划分为多个部分。现在对于每个部分,我都编写了一组正则表达式来提取某些数据。我正在尝试逐个查找并阅读每个部分并打印该部分的数据。但是我没有得到任何输出。
我的部分文件如下:
LOAD: -U-: Sent: ID101 USD50000 None
LOAD: ............data................
LOAD: -U-: Sent: ID202 RUP30000 124ui
LOAD:.............data...............
使得每个部分如下:
LOAD: -U-: Sent: ID101 USD50000 None
LOAD: ............data................ (till here)
这是我正在使用的代码:
block=0
with open("file.txt") as f:
for line in f:
if '-U-:Sent' in line: #creating blocks or sections
block+=1
print("--------Block"+str(block)+"-------")
print(line)
for l in line.splitlines(): #to go through each section
m=re.findall(r'--------Block', l) #find sections and then read through them
if m:
#regex operation lines (same for all sections)
我希望找到每个部分,然后为每个部分进行正则表达式提取:
-------Block------
{'ID':'101', 'Currency' : 'USD'}
(提取代码已编写,我只需要找到每个块并通过每个块运行提取代码)但实际输出为空。如何更改代码以获得所需的输出?
【问题讨论】:
-
你能用文本输入文件指定你的预期输出吗?