gpt4 book ai didi

python - 使用正则表达式在 Python 中的两个已定义标签之间查找所有出现的多行字符串

转载 作者:行者123 更新时间:2023-12-04 09:28:28 27 4
gpt4 key购买 nike

我正在尝试做一些出乎意料的事情。我想解析一个 Python 代码,其中一些特定的注释行定义了我想要提取的文本 block 或代码块。对于这个例子,我将使用两种类型的标签,一种用于代码,一种用于文本描述。

#c
print ("this is the tag I used for code I want to find")
#-c

#d
"""This is the tag I used for a description I want to find"""
#-d
为什么我要这样标记我的代码?嗯,这是另一个问题。更多详情请查看 this SO post如果你感兴趣。
现在,我一直在尝试用正则表达式捕获这些标签,因为这是我第一次使用正则表达式,我显然没有成功......这是我目前的尝试:
file = 'script.py'
with open(file, 'r') as f:
text = f.read()
text = read_python_script(file)

code_blocks = re.compile(r'(?s)(?<=#c\n)(.*\n)(?=#-c)')
desc_blocks = re.compile(r'(?s)(?<=#d\n)(.*\n)(?=#-d)')

code = re.findall(code_blocks, text)
desc = re.findall(desc_blocks, text)
这是我要解析的脚本示例:
# -*- coding: utf-8 -*-
"""
Title: blablabla
Author: Mathieu

Description: Report the some measurements
"""

import time
import uuid

from database.model import TestLimit, TestResult
from util import log

#d
"""
blablabla some description
which might be multiline
"""
#-d
# Constants
#c
CONSTANT_1 = 10 # Unit
CONSTANT_2 = 2 # Unit
#-c

class Foo(Fp):
def __init__(self, #some parameters):
# some init

def _run(self, #some parameters):
#%% Section Title 1
#%%% Sub section Title 1
#c
code I would like to catch
can be multiple liens
#-c


with something.open():
#%%% Sub section title 2
#d
"""some description I want to catch"""
#-d

#c
some more code I want to catch
#-c
目前,我只得到第一次出现,我不知道为什么......
编辑:如前所述,我应该将表达式更改为惰性格式:
r'(?s)(?<=#c\n)(.*?)(?=\n#-c)'
这并不能完全解决问题,因为我仍然只发现第一次出现。

最佳答案

您可以使用

re.findall(r'(?s)#c\n(.*?)\n[^\S\r\n]*#-c', text)
regex demo .
这里有两件事:
  • 懒惰匹配.*?图案
  • [^\S\r\n]*匹配 #-c 之前必须使用的任何 0 个或多个水平空格因为符号前可能有一些缩进。

  • 详情
  • (?s) - 内联re.DOTALL修饰符
  • #c - 文字字符串
  • \n - 换行符
  • (.*?) - 捕获组 1:尽可能少的任何零个或多个字符
  • \n - 换行符
  • [^\S\r\n]* - 0 个或多个水平空白字符
  • #-c - 文字字符串。
  • 关于python - 使用正则表达式在 Python 中的两个已定义标签之间查找所有出现的多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62934273/

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