给定类定义的代码,我试图提取所有属性及其注释(如果没有注释,则为""个空字符串).

class Player(Schema):
    score = fields.Float()
    """
    Total points from killing zombies and finding treasures
    """

    name = fields.String()
    age = fields.Int()

    backpack = fields.Nested(
        PlayerBackpackInventoryItem,
        missing=[PlayerBackpackInventoryItem.from_name("knife")],
    )
    """
    Collection of items that a player can store in their backpack
    """

在上面的示例中,我们预期解析结果为:

[
  ("score", "Total points from killing zombies and finding treasures"),
  ("name", ""),
  ("age", ""),
  ("backpack", "Collection of items that a player can store in their backpack")
]

在我下面的try 中,它未能正确提取 comments ,并给出了输出:

[
  ('score', 'Total points from killing zombies and finding treasures'), 
  ('name', ''), 
  ('age', ''), 
  ('backpack', '')
]

如何修复正则表达式(甚至整个解析逻辑)以处理示例类代码中出现的情况?

谢谢

import re

code_block = '''class Player(Schema):
    score = fields.Float()
    """
    Total points from killing zombies and finding treasures
    """

    name = fields.String()
    age = fields.Int()

    backpack = fields.Nested(
        PlayerBackpackInventoryItem,
        missing=[PlayerBackpackInventoryItem.from_name("knife")],
    )
    """
    Collection of items that a player can store in their backpack
    """
'''


def parse_schema_comments(code):
    # Regular expression pattern to match field names and multiline comments
    pattern = r'(\w+)\s*=\s*fields\.\w+\([^\)]*\)(?:\n\s*"""\n(.*?)\n\s*""")?'

    # Find all matches using the pattern
    matches = re.findall(pattern, code, re.DOTALL)

    # Process the matches to format them as required
    result = []
    for match in matches:
        field_name, comment = match
        comment = comment.strip() if comment else ""
        result.append((field_name, comment))

    return result


parsed_comments = parse_schema_comments(code_block)
print(parsed_comments)

推荐答案

 pattern = r'(\w+)\s*=\s*fields\.\w+\(.*?\)\n(?:\s*"""\s*([\s\S]*?)\s*"""\s*)?'

更新模式会产生以下输出:

 [('score', 'Total points from killing zombies and finding treasures'),
 ('name', ''),
 ('age', ''),
 ('backpack', 'Collection of items that a player can store in their backpack')]

Python相关问答推荐

从包含基本数据描述的文本字段中识别和检索特定字符序列

自动编码器和极坐标

将numpy矩阵映射到字符串矩阵

如何防止Plotly在输出到PDF时减少行中的点数?

如何计算列表列行之间的公共元素

将HLS纳入媒体包

仿制药的类型铸造

如何在箱形图中添加绘制线的传奇?

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

用Python解密Java加密文件

使用@ guardlasses. guardlass和注释的Python继承

当点击tkinter菜单而不是菜单选项时,如何执行命令?

如何保持服务器发送的事件连接活动?

合并帧,但不按合并键排序

Django admin Csrf令牌未设置

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

导入错误:无法导入名称';操作';

在Python中从嵌套的for循环中获取插值

polars:有效的方法来应用函数过滤列的字符串

在numpy数组中寻找楼梯状 struct