繁体   English   中英

python 正则表达式删除评论

[英]python regex to remove comments

我将如何编写一个正则表达式来删除所有以 # 开头并在行尾停止的注释 - 但同时排除前两行说

#!/usr/bin/python 

#-*- coding: utf-8 -*-

您可以通过使用tokenize.generate_tokens解析 Python 代码来删除注释。 以下是文档中此示例的略微修改版本:

import tokenize
import io
import sys
if sys.version_info[0] == 3:
    StringIO = io.StringIO
else:
    StringIO = io.BytesIO

def nocomment(s):
    result = []
    g = tokenize.generate_tokens(StringIO(s).readline)  
    for toknum, tokval, _, _, _  in g:
        # print(toknum,tokval)
        if toknum != tokenize.COMMENT:
            result.append((toknum, tokval))
    return tokenize.untokenize(result)

with open('script.py','r') as f:
    content=f.read()

print(nocomment(content))

例如:

如果 script.py 包含

def foo(): # Remove this comment
    ''' But do not remove this #1 docstring 
    '''
    # Another comment
    pass

那么 nocomment 的nocomment

def foo ():
    ''' But do not remove this #1 docstring 
    '''

    pass 

我实际上并不认为这可以纯粹使用正则表达式来完成,因为您需要计算引号以确保#的实例不在字符串内。

我会查看python 的内置代码解析模块以寻求类似的帮助。

sed -e '1,2p' -e '/^\s*#/d' infile

然后将其包装在subprocess.Popen调用中。

但是,这不能替代真正的解析器? 为什么会感兴趣,嗯:假设这个 Python 脚本:

output = """
This is
#1 of 100"""

繁荣,任何非解析解决方案都会立即破坏您的脚本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM