gpt4 book ai didi

python - 正则表达式读取文件并返回Python文件内部匹配模式后的第一行

转载 作者:行者123 更新时间:2023-12-01 00:49:16 25 4
gpt4 key购买 nike

示例字符串 1:

7.2.P.8.1 

Summary and Conclusion


A stability study with two batches was carried out.

示例字符串 2:

7.2.S.1.2  

Structure

Not applicable as the substance is not present.

我想编写一个正则表达式来获取此表单后的第一行 (7.2.P.8.1 ) 或 (7.2.S.1.2 ) 或 (8-3-1-P-2) 或任何其他格式(所有内容都将由 . 或 -) 分隔并检索它。所以从一开始我需要作为输出(摘要和结论)和第二个实例(结构)的实例。 “示例字符串”一词不会成为文件内容的一部分,仅用于显示示例。

也许有时格式会是这样的:

9.2.P.8.1 Summary and Conclusion  

A stability study with two batches was carried out.

在这种情况下,我也想检索作为输出:摘要和结论

注意:我只想从文件中检索第一个匹配模式,而不是所有匹配项,因此我的代码在找到第一个匹配模式后应该会中断。我怎样才能有效地做到这一点。

到目前为止的代码:

import re
def func():
with open('/path/to/file.txt') as f: # Open the file (auto-close it too)
for line in f: # Go through the lines one at a time
m = re.match('\d+(?:[.-]\w+)*\s*', line) # Check each line
if m: # If we have a match...
return m.group(1) # ...return the value

最佳答案

您可以使用

import re

rx = re.compile(r'\d+(?:[.-]\w+)*\s*(\S.*)?$')
found = False
with open('/path/to/file.txt', 'r') as f:
for line in f:
if not found: # If the required line is not found yet
m = rx.match(line.strip()) # Check if matching line found
if m:
if m.group(1): # If Group 1 is not empty
print(m.group(1)) # Print it
break # Stop processing
else: # Else, the next blank line is necessary
found=True # Set found flag to True
else:
if not line.strip(): # Skip blank line
pass
else:
print(line.strip()) # Else, print the match
break # Stop processing

请参阅Python demoregex demo .

注释

\d+(?:[.-]\w+)*\s*(\S.*)?$ 正则表达式搜索 1+ 位数字,然后搜索 0 次或多次重复 .- 后跟 1+ 个单词字符,然后尝试匹配 0+ 个空格,然后将后跟的任何非空格字符捕获到第 1 组中任何 0+ 个字符直到行尾。如果组 1 不为空,则找到匹配项并且 break 停止处理。

否则,found bool 标志将设置为 True 并返回下一个非空行。

关于python - 正则表达式读取文件并返回Python文件内部匹配模式后的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56702217/

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