【问题标题】:Find and traverse each section in a file?查找并遍历文件中的每个部分?
【发布时间】: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'}

(提取代码已编写,我只需要找到每个块并通过每个块运行提取代码)但实际输出为空。如何更改代码以获得所需的输出?

【问题讨论】:

  • 你能用文本输入文件指定你的预期输出吗?

标签: python regex


【解决方案1】:

您可以使用file.read() 简单地读取单个字符串中的整个文件,然后使用python re 模块和字符串split()strip() 方法对其进行清理,以直接获取所需数据的列表。

试试这个:

import re
with open("your_file_name") as file:
    blocks = [re.sub('LOAD.*','',section).strip(" \n\n") for section in file.read().split("LOAD: -U-: Sent:")][1:]
print(blocks)

输出

['ID101 USD50000 None', 'ID202 RUP30000 124ui']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多