gpt4 book ai didi

python - 另一个正则表达式问题

转载 作者:行者123 更新时间:2023-11-28 22:42:10 24 4
gpt4 key购买 nike

我有一个包含以下行的文件:

2015-08-11 13:31:06.609 CEST [SwitchEvent Thread] INFO  o.o.t.t.internal.learning.Learning - Probabilities for Host 1:  [Switch 1: 1.0]
2015-08-11 13:31:07.349 CEST [SwitchEvent Thread] INFO o.o.t.t.internal.learning.Learning - Probabilities for Host 1: [Switch 1: 0.5, Switch 2: 0.5]

我想得到它的最后一部分(例如,在第 1 行中,我想得到 [Switch 1: 1.0])

为此,我有这个模式:(\[Switch .*\])
这是我正在使用的(部分)代码:

import os
import sys
import re

data_pattern = re.compile('(\[Switch .*\])')

f = open('some_file', 'r')
for line in f:
print line
data_match = data_pattern.match(line)
print data_match.group(0)

整个事情导致崩溃:

Traceback (most recent call last):
File "/home/nemo-develop/PycharmProjects/Affinity-Remote/learning_data_preparation.py", line 62, in <module>
read_file(join(directory, filename), switch_amount)
File "/home/nemo-develop/PycharmProjects/Affinity-Remote/learning_data_preparation.py", line 33, in read_file
print data_match.group(0)
AttributeError: 'NoneType' object has no attribute 'group'
2015-08-11 13:31:06.609 CEST [SwitchEvent Thread] INFO o.o.t.t.internal.learning.Learning - Probabilities for Host 1: [Switch 1: 1.0]

所以行不匹配。
我还检查了 regex101。它似乎在那里工作.. Here is a link to it .

出了什么问题?
谢谢

最佳答案

如果模式不在行首,则需要使用搜索,除非模式在行首,否则匹配失败:

import re
data_pattern = re.compile(r'(\[Switch .*\])')

f = open('some_file', 'r')
for line in f:
print line
# CHANGE TO RE.SEARCH HERE:
data_match = data_pattern.search(line)
print data_match.group(0)

关于python - 另一个正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942960/

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