我想删除python文件中的所有注释。 文件如下: ---------------comment.py------------------
# this is comment line.
age = 18 # comment in line
msg1 = "I'm #1." # comment. there's a # in code.
msg2 = 'you are #2. ' + 'He is #3' # strange sign ' # ' in comment.
print('Waiting your answer')
我编写了许多正则表达式来提取所有注释,其中一些如下:
(?(?<=['"])(?<=['"])\s*#.*$|\s*#.*$)
get: #1." # comment. there's a # in code.
(?<=('|")[^\1]*\1)\s*#.*$|\s*#.*$
wrong. it's not 0-width in lookaround (?<=..)
但它不能正常工作。什么是正确的正则表达式? 你能帮帮我吗
您可以尝试使用
tokenize
而不是regex
,正如@OlvinRoght所说,在这种情况下,使用regex解析代码可能是个坏主意。如您所见here,您可以尝试以下方法来检测注释:输出:
然后,为了获得预期的结果,即不带注释的python文件,您可以尝试以下方法:
输出:
信用证:https://gist.github.com/BroHui/aca2b8e6e6bdf3cb4af4b246c9837fa3
这就行了。它使用标记化。您可以根据自己的使用情况修改此代码
text.txt:
输出:
输入:
输出:
相关问题 更多 >
编程相关推荐