大家好,我已经看到了几种使用tokenizer提取python注释的解决方案,并寻找
tokenize.COMMENT但是,我找不到任何示例来说明如何对多行注释执行此操作。例如,考虑下面的readme.py文件
"""
multiline comment above class read me
read me too
"""
# dont read mee
class TestComment:
"""
multiline inside class
"""
def aFunc(self):
pass我如何像上面的例子一样提取多行注释的内容?
发布于 2021-05-01 22:29:40
tokenize.COMMENT可以用于注释(以#开头),而不能用于多行字符串、文字或文档字符串。
但是,您可以使用此正则表达式从示例中提取多行字符串:
import re
file = "file.py"
with open(file, "r") as f:
content = f.read()
p = re.compile('(?:""")(.*?)(?:""")', re.DOTALL)
result = p.findall(content)
print(result)输出:
['\nmultiline comment above class read me\nread me too\n', '\n multiline inside class\n ']如果您想保留“”,只需使用捕获组而不是非捕获组:用(?:""")代替(""")。
使用re.DOTALL很重要,它允许点.匹配任何字符,包括换行符。
一个小警告:
请注意,正如@edusanketd在注释中所说,此正则表达式也将匹配在常规字符串或单行注释中使用的三重引号。所以,这个正则表达式并不是万能的:如果你所有的python文件都是像你的例子中那样构造的("""只用于多行字符串),那就没问题了,但是如果你有一些将"""用于其他目的的文件(比如在常规字符串中使用的三重引号字符串),它们将会出现一些“错误”。
示例代码显示了此正则表达式的限制:
"""
multiline comment above class read me
read me too
"""
# dont read mee
class TestComment:
"""
multiline inside class
"""
def aFunc(self):
pass
a_string = '"""THIS IS NOT A COMMENT"""'
# """dont read me too"""输出:
['\nmultiline comment above class read me\nread me too\n', '\n multiline inside class\n ', 'THIS IS NOT A COMMENT', 'dont read me too']将有关多行字符串的一些信息作为多行注释进行 :
来自Guido van Rossum的推文:
https://twitter.com/gvanrossum/status/112670605505077248?lang=en
Python提示:您可以将多行字符串用作多行注释。除非用作文档字符串,否则它们不会生成任何代码!:-)
这是Sean Gillie关于这个话题的一个有趣的帖子:
https://sgillies.net/2017/05/30/python-multi-line-comments-and-triple-quoted-strings.html
发布于 2021-05-01 20:57:36
python中的所谓multiline comments实际上被视为docstrings。通常,文档字符串与python中的类相关联。可以使用objname.__doc__检索。在这里,objname替换与docstring关联的直接class或function。
例如,
class ex:
"""dufvdv"""
def __init__(self):
# single line cmt
""" multiline inside function
another line """
pass在这里使用__doc__的过程如下:
>>> ex.__doc__
'dufvdv'
>>> ex.__init__.__doc__
' multiline inside function\nanother line'据我所知,您期望的是一种从代码中提取所有multiline comments的内置技术,但这并不存在。
因此,您可以相应地使用__doc__。
https://stackoverflow.com/questions/67346210
复制相似问题