def remove_comments(line):
if line.startswith('/*') or line.endsswith('*/'):
return 0
else:
return 1
count = sum(remove_comments(line) for line in f if line.strip())
with open("test", 'r') as f_in:
f = f_in.readlines()
is_in_comment = False
def remove_comments(line):
global is_in_comment
line = line.strip()
if line.startswith('/*'):
is_in_comment = True
return 0
elif line.endswith('*/'):
is_in_comment = False
return 0
return 0 if is_in_comment else 1
count = sum(remove_comments(line) for line in f if line.strip())
但是,这假设您不能拥有没有前一个/*的*/。此代码为以下test文件返回3:
That is one line
Another
/* Comment
Other comment
End comment */
Final line, not a comment
一个肮脏的黑客可能是使用全局变量:
但是,这假设您不能拥有没有前一个
/*
的*/
。此代码为以下test
文件返回3:相关问题 更多 >
编程相关推荐