我想按如下方式決議 Python 檔案字串:
Summary of class that is multiple lines.
Parameters
----------
param1 : str
Param 1 is a param
Returns
-------
value : str
Examples
--------
>>> print()
映射到
{
'base': 'Summary of class that is multiple lines.',
'params': 'param1 : str\n\tParam 1 is a param',
'returns': 'value : str',
'examples': '>>> print()'
}
這對于命名組和 非常簡單re.match.groupdict,但我遇到的問題是這四個組中的每一個都是可選的。這里有幾個關于可選組的問題,特別是這個似乎相關,但它有很好的結束字符來分解事情。此檔案字串可以包含任何字符(當前使用[\s\S])。
uj5u.com熱心網友回復:
我認為這應該有效:
^(?P<base>[\s\S] ?)??(?:(?:^|\n\n)Parameters\n-{10}\n(?P<params>[\s\S]*?))?(?:(?:^|\n\n)Returns\n-{7}\n(?P<returns>[\s\S]*?))?(?:(?:^|\n\n)Examples\n-{8}\n(?P<examples>[\s\S]*))?$
我用來生成這個正則運算式的代碼:
import re
sep_regex = r"(?:^|\n\n)"
summary_regex = r"(?P<base>[\s\S] ?)"
param_regex = rf"(?:{sep_regex}Parameters\n-{{10}}\n(?P<params>[\s\S]*?))"
returns_regex = rf"(?:{sep_regex}Returns\n-{{7}}\n(?P<returns>[\s\S]*?))"
examples_regex = rf"(?:{sep_regex}Examples\n-{{8}}\n(?P<examples>[\s\S]*))"
combined_regex = rf"^{summary_regex}??{param_regex}?{returns_regex}?{examples_regex}?$"
print(combined_regex)
例子:
from pprint import pprint
match = re.search(combined_regex, text) # text being your example text
pprint(match.groupdict())
# out: {'base': 'Summary of class that is multiple lines.',
# out: 'examples': '>>> print()',
# out: 'params': 'param1 : str\n Param 1 is a param',
# out: 'returns': 'value : str'}
我還使用洗掉的檔案字串的各個部分對其進行了測驗。
uj5u.com熱心網友回復:
您可以使用現有的庫來決議檔案字串,而不是撰寫自己的正則運算式,其作者已經為您完成了艱苦的作業。
我使用docstring-parser包整理了一個示例。要安裝此軟體包,您需要運行以下命令:
pip install docstring-parser
然后您可以使用以下代碼來決議您的檔案字串:
from docstring_parser import parse
docstring_text = """Summary of class that is multiple lines.
Parameters
----------
param1 : str
Param 1 is a param
Returns
-------
value : str
Examples
--------
>>> print()
"""
docstring = parse(docstring_text)
docstring_info = {
"base": docstring.short_description,
"params": [
{
"name": param.arg_name,
"type": param.type_name,
"description": param.description,
}
for param in docstring.params
],
"returns": {
"name": docstring.returns.return_name,
"type": docstring.returns.type_name,
}
if docstring.returns
else {},
"examples": [{"snippet": example.snippet} for example in docstring.examples],
}
print(docstring_info)
這給出了以下輸出(為清楚起見添加了縮進):
{
"base": "Summary of class that is multiple lines.",
"params": [{"name": "param1", "type": "str", "description": "Param 1 is a param"}],
"returns": {"name": "value", "type": "str"},
"examples": [{"snippet": ">>> print()"}],
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475175.html
