Python 在读取文件时,是否可以使用正则表达式忽略文本块
我不确定我是从错误的角度来看这个问题,但我是一个初学者,有点超出了我的深度。我试图在读取文件时忽略多行注释,以便计算.sas文件(仅为文本文件)中的代码行数。我可以让我的代码找到分成两行的注释,就像这样Python 在读取文件时,是否可以使用正则表达式忽略文本块,python,regex,count,file-read,Python,Regex,Count,File Read,我不确定我是从错误的角度来看这个问题,但我是一个初学者,有点超出了我的深度。我试图在读取文件时忽略多行注释,以便计算.sas文件(仅为文本文件)中的代码行数。我可以让我的代码找到分成两行的注释,就像这样 /* comment comment*/ 但不是这样 /* comment comment comment */ 我的代码是 for file_name in find_files(d): with open(file_name, 'r') as f: def rem
/* comment
comment*/
但不是这样
/* comment
comment
comment */
我的代码是
for file_name in find_files(d):
with open(file_name, 'r') as f:
def remove_comments(line):
is_in_comment = False
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())
print(count)
这不适用于多行注释。我已经通过使用正则表达式找到了多行注释。下面是代码,我能想到的唯一方法是使用re.sub()写回文件,然后进行计数。读入时是否可以忽略正则表达式匹配?还是我走远了
for file_name in find_files(d):
with open(file_name, 'r') as f:
data = f.read()
multiline_comments = re.findall(pattern, data, re.DOTALL)
print(multiline_comments)
难道你不能逐行读取文件并使用多行模式检查它吗。如果它包含没有结束的开始注释块,请使用bool标志,该标志允许您忽略计数器中的下一行,直到遇到结束注释块,然后按正常方式解析,直到下一个注释块。我最后这样做:)