python是怎么实现过滤 #注释代码的?
巴扎黑
巴扎黑 2017-04-18 10:29:44
0
2
571

今天看python核心编程看到一个问题,题意大概就是过滤一个file-like对象里“#”的注释部分,然后输出其他部分。简单情形下,另写一行的#注释比较好判断,用startwith('#')匹配应该能满足。问题在于那些写在正常业务代码之后的注释,该如何过滤之?举个例子:

if name.find(",") == -1:#Annotations
    pass

请问有没有人了解它是怎么过滤这种注释的?谢谢。

巴扎黑
巴扎黑

reply all(2)
大家讲道理

Let’s talk about the idea
If you don’t consider the # in the string, it is very convenient to use re to match

#[^\n]*?\n

is enough
If you consider that the # in the string is slightly more complicated, match:

#[^'"]*?\n

Barely able to cope with most situations

The disadvantage is that for

'a' # 'b'

Such a statement cannot be matched because Python's re does not support balanced groups.

大家讲道理

Just use regular matching#It won’t work until the end of the line.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template