python查找行中的数字字符串

2024-10-02 20:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这种长日志文件

2012-02-03 18:35:34 SampleClass6 [INFO] everything normal for id 174025851
2012-02-03 18:35:34 SampleClass4 [FATAL] system problem at id 1991740254
2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 1304807656
2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740

我想准确地找到id=1740,并打印行,但id=174025851也在其中。如何在一行和打印行中准确地找到字符串id=1740

for line in f: 
    if str(id) in line: 
        print(line)

它还打印第一行和第二行,但我只想第四行,id为1740


Tags: 文件ininfoidforlinesystemat
3条回答

冒着为一个已经有很多答案的问题添加另一个答案的风险,下面是我认为正则表达式解析器在这里的最佳使用方式:

import re

the_id = 1740

with open("test.txt") as f:
    for line in f:
        match = re.search("id\s+(\d+)\s*$", line)
        if match and the_id == int(match.group(1)):
            print(line, end='')

这使得:

2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740

您在这里所做的是使用解析器查找以以下内容结尾的行:“id”,后跟空格,后跟一个或多个数字(您在一个组中捕获),可以选择后跟任意数量的空格

然后将捕获的组转换为int并与id进行比较

顺便说一句,id存储在名为the_id的变量中,因为id是内置函数的名称,因此不是一个好的变量名称选择(干扰内置函数的使用)


更新

<> P.Askter现在已经澄清,ID可以出现在直线的中间,不一定在末端。p>

这可以通过对正则表达式进行简单的调整来轻松处理。将上述代码中的相关行更改为:

        match = re.search("id\s+(\d+)", line)

现在删除对数字之后应该出现的内容的任何检查

因为表示“一个或多个”的+也是贪心的(也就是说,它尽可能多地匹配与其相关的模式的部分),ID的整体由括号中的组匹配,而不需要指定它后面的内容

给定输入文件

2012-02-03 18:35:34 SampleClass6 [INFO] everything normal for id 174025851
2012-02-03 18:35:34 SampleClass4 [FATAL] system problem at id 1991740254
2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 1304807656
2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740
2012-02-03 19:11:02 id 1740 SampleClass5 [TRACE] verbose detail

现在将输出:

2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740
2012-02-03 19:11:02 id 1740 SampleClass5 [TRACE] verbose detail

您可以使用正则表达式

import re
text = """
2012-02-03 18:35:34 SampleClass6 [INFO] everything normal for id 174025851
2012-02-03 18:35:34 SampleClass4 [FATAL] system problem at id 1991740254
2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 1304807656
2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740
"""

# the \s means the char after 0 must be a space, tab or newline (so, not a number)
p = re.compile(r'.*id 1740\s') 
ls = p.findall(text)

您可以使用regex,比如id后跟空格。 或者如果id始终位于行的末尾。然后使用 如果line.endswith('id'+id)为true,则执行逻辑

相关问题 更多 >