【发布时间】:2019-08-25 12:46:34
【问题描述】:
我想逐行迭代文本文件并搜索模式并从中提取实体。但是,提取的几个模式具有多行特征,当我逐行迭代时会丢失这些特征。
现在,我正在使用 try-except 块并将下一行附加到当前行,例如:
try:
id_value, utterance, prediction = process(line + ' ' + lines[n + 1])
except AttributeError:
# Handle bad data
try:
id_value, utterance, prediction = process(line + ' ' + lines[n + 1] + ' ' + lines[n + 2])
except AttributeError:
# Handle bad data
try:
id_value, utterance, prediction = process(
line + ' ' + lines[n + 1] + ' ' + lines[n + 2] + ' ' + lines[n + 3])
这是数据:
数据.txt
[22 Aug 2019 13:25:12] [ID:9ea1566460506294] INFO [139921763325696] (ModelClassification:056) - Model classification for utterance_1 is 1
[22 Aug 2019 13:26:06] [ID:7ea1566460117776] INFO [139921771718400] (ModelClassification:056) - Model classification for utterance_2
is 1
[22 Aug 2019 13:26:16] [ID:71d1566460492762] INFO [139921771718400] (ModelClassification:056) - Model classification for utterance_3 is 0
如你所见
[22 Aug 2019 13:26:06] [ID:7ea1566460117776] INFO [139921771718400] (ModelClassification:056) - Model classification for utterance_2
is 1
在逐行迭代时扩展 2 行。
代码
import re
matching_string = 'Model classification for'
id_start_string = '[ID:'
id_end_string = ']'
def process(line):
start_idx = line.find(id_start_string)
end_idx = [s.start() for s in re.finditer(id_end_string, line)]
for end in end_idx:
if end > start_idx:
# Get first index greater than start string index
end_idx = end
break
id_value = line[start_idx + len(id_start_string): end_idx]
groups = re.search('Model classification for (.*) is (0|1)', line).groups()
utterance = groups[0]
prediction = groups[1]
return id_value, utterance, prediction
with open('data.txt', 'r') as f:
lines = f.read().splitlines()
for n, line in enumerate(lines):
# Search for pattern in string
if matching_string in line:
try:
id_value, utterance, prediction = process(line)
except AttributeError:
print('Bad data')
print(line)
print(id_value, utterance, prediction)
我的问题可以有递归解决方案吗?非常感谢任何帮助。
编辑 -
lines = ['22 Aug 2019 13:25:12] [ID:9ea1566460506294] INFO [139921763325696] (ModelClassification:056) - Model classification for utterance_1 is 1', '[22 Aug 2019 13:26:06] [ID:7ea1566460117776] INFO [139921771718400] (ModelClassification:056) - Model classification for utterance_2', ' is 1', '[22 Aug 2019 13:26:16] [ID:71d1566460492762] INFO [139921771718400] (ModelClassification:056) - Model classification for utterance_3 is 0 ']
【问题讨论】:
-
您能否扩展您的代码,使其不依赖于未指定的
data.txt文件?只需对字符串数组进行硬编码,这就是您在lines中得到的内容,希望不会导致问题(请验证!)。 -
编辑了我的问题。
data.txt已指定。 -
不,不要添加编辑部分。提取并提供minimal reproducible example 应该是您的目标。