使用Python正则表达式移除注释
我该如何写一个正则表达式,来去掉所有以#开头的注释,并且这些注释会一直到行末结束——同时又要排除前两行,这两行内容是
#!/usr/bin/python
和
#-*- coding: utf-8 -*-
3 个回答
1
sed -e '1,2p' -e '/^\s*#/d' infile
然后把这个放在一个 subprocess.Popen
的调用里。
不过,这个 并不能 代替真正的解析器!这有什么意义呢?假设有这样一个Python脚本:
output = """
This is
#1 of 100"""
哗啦,任何不进行解析的解决方案都会让你的脚本立刻出问题。
1
我觉得光靠正则表达式是做不到的,因为你需要计算引号的数量,以确保#
这个符号不是在字符串里面。
我建议你看看Python自带的代码解析模块,这些可以帮助你处理类似的问题。
5
你可以通过使用 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
的输出结果是
def foo ():
''' But do not remove this #1 docstring
'''
pass