python - 在 python 中读取时忽略文本文件中的多行注释
问题描述
我正在尝试使用 python 脚本计算目录中多个文本文件中有多少行代码。我想出了以下方法,但它仅在注释在一行而不是多行时才有效。有没有办法做到这一点?
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
推荐阅读
- excel-formula - 带有事物列表的 Excel 搜索功能 - 数组的行为很奇怪?
- c# - .net 上的 Ghostscript 安装问题
- reactjs - React Hooks:如何在渲染之前等待数据被获取
- python - 错误:尝试使用 BeautifulSoup 抓取数据时无
- javascript - 如何在 HTML 中显示我的 JS 游戏的分数?
- unity3d - UnityWebRequest 为正确的 url 返回不同的错误
- java - 如何为“keep_screen_ON”的开启和关闭创建设置
- django - 在位于 settings.py 的视图中调用函数
- c# - 使用具有通用查询性能的 AsCacheQueryable 从 Ignite 获取数据
- pandas - Pandas 用预定义的值替换单元格值