4
當我試圖使用pycparser
有意見我ParseErrorPycparser失敗的意見
import pycparser
parser = pycparser.CParser()
parser.parse("int main(void){return 0;}")
parser.parse("/* comment */ int main(void){return 0;}")
Traceback (most recent call last):
File "test_pycparser.py", line 18, in <module> parser.parse("/* comment */ int main(void){return 0;}")
File "build\bdist.win32\egg\pycparser\c_parser.py", line 124, in parse
File "build\bdist.win32\egg\pycparser\ply\yacc.py", line 265, in parse
File "build\bdist.win32\egg\pycparser\ply\yacc.py", line 1047, in parseopt_notrack
File "build\bdist.win32\egg\pycparser\c_parser.py", line 1423, in p_error
File "build\bdist.win32\egg\pycparser\plyparser.py", line 54, in _parse_error
pycparser.plyparser.ParseError: :1:1: before:/
解決方案解析文件:pycparser
在當前版本不支持源代碼註釋,但this fork允許它,或者你可以使用來自問題Python snippet to remove C and C++ comments的配方從源代碼中刪除評論。
import pycparser
import re
def comment_remover(text):
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return ""
else:
return s
pattern = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE
)
return re.sub(pattern, replacer, text)
parser = pycparser.CParser(keep_comment=True)
parser.parse("int main(void){return 0;}")
parser.parse("/* comment */ int main(void){return 0;}")
parser_2 = pycparser.CParser()
parser.parse(comment_remover("/* comment */ int main(void){return 0;}"))