gpt4 book ai didi

Python:使用正则表达式获取文件行中的特定文本

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:16 25 4
gpt4 key购买 nike

我正在使用 python 逐行搜索文本日志文件,我想将一行的特定部分保存为变量。我正在使用 Regex,但我认为我没有正确使用它,因为我的变量 string_I_want 总是得到 None。我在这里查看其他 Regex 问题,看到人们将 .group() 添加到他们的 re.search 末尾,但这给了我一个错误。我不是最熟悉 Regex 的人,但不知道我哪里出错了?

示例日志文件:

2016-03-08 11:23:25  test_data:0317: m=string_I_want max_count: 17655, avg_size: 320, avg_rate: 165

我的脚本:

def get_data(log_file):

#Read file line by line
with open(log_file) as f:
f = f.readlines()

for line in f:
date = line[0:10]
time = line[11:19]

string_I_want=re.search(r'/m=\w*/g',line)

print date, time, string_I_want

最佳答案

您需要删除带有全局标志的 /.../ 分隔符,并使用捕获组:

mObj = re.search(r'm=(\w+)',line)
if mObj:
string_I_want = mObj.group(1)

查看此 regex demoPython demo :

import re
p = r'm=(\w+)' # Init the regex with a raw string literal (so, no need to use \\w, just \w is enough)
s = "2016-03-08 11:23:25 test_data:0317: m=string_I_want max_count: 17655, avg_size: 320, avg_rate: 165"
mObj = re.search(p, s) # Execute a regex-based search
if mObj: # Check if we got a match
print(mObj.group(1)) # DEMO: Print the Group 1 value

图案细节:

  • m= - 匹配 m= 文字字符序列(如果必须匹配整个单词,则在之前添加空格或 \b)
  • (\w+) - 第 1 组捕获 1+ 个字母数字或下划线字符。我们可以使用 .group(1) 方法引用此值。

关于Python:使用正则表达式获取文件行中的特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com