【问题标题】:creating list of strings that matches regex pattern while iterating through multiple files在遍历多个文件时创建与正则表达式模式匹配的字符串列表
【发布时间】:2020-08-25 17:08:13
【问题描述】:

我正在遍历一个目录中的文件。它们都具有相同的结构:

3.1  Receiver Type            : ASHTECH UZ-12
     Satellite System         : GPS
     Serial Number            : UC2200303016
     Firmware Version         : CN00
     Elevation Cutoff Setting : 3 deg
     Date Installed           : 2008-07-15T00:00Z
     Date Removed             : 2008-12-29T00:00Z
     Temperature Stabiliz.    : NONE
     Additional Information   : 


3.3  Receiver Type            : TRIMBLE NETR5
     Satellite System         : GPS+GLO
     Serial Number            : 4917K61764
     Firmware Version         : 4.03
     Elevation Cutoff Setting : 3 deg
     Date Installed           : 2009-10-15T20:00Z
     Date Removed             : 2010-08-27T12:00Z
     Temperature Stabiliz.    : 
     Additional Information   : 

我想创建接收器类型列表 (['ASHTECH UZ-12', 'TRIMBLE NETR', ...]),但我创建的函数返回空列表列表,可能是使用了错误的正则表达式,但我不知道如何修复它。有人可以帮忙吗?这是函数:

def logs_reader():
    path = Path("C:\\Users\\" + getpass.getuser() + "\\DCBviz\\logs\\")

    file_list = [f for f in path.glob('**/*.log') if f.is_file()]
    
    receiver_list = []
    for file in file_list:
        with open(file, encoding='utf8') as f:
            receiver_models = re.findall('.^Receiver type.:*(\S+\n)', f.read())
            receiver_list.append(receiver_models)
            print(receiver_list)
logs_reader()

【问题讨论】:

  • . 之后有一个行首锚点 (^),需要一个字符来匹配它——这并不奇怪整个正则表达式不匹配任何东西。
  • 你可以使用re.findall("Receiver Type\s*:\s*(.*?)\s*$", f.read(), re.MULTILINE)

标签: python regex list


【解决方案1】:

我们试试吧,

print(
    [x.split(":")[-1].strip() for x in text.splitlines() if "Receiver Type" in x]
)

import re

print(
    [x.strip() for x in re.findall("Receiver Type\s+:(.+)", text)]
)

['ASHTECH UZ-12', 'TRIMBLE NETR5']

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2014-04-10
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多