str.startswith() 未如预期工作
我不明白为什么这个不行。我在对传给函数的字符串使用lstrip(),然后想看看它是否以"""开头。但不知怎么的,它陷入了无限循环。
def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
这是我的输出:
Enter the file name: test.txt
import re
def count_loc(infile):
这里是我正在读取的文件的开头,供参考:
import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
5 个回答
1
只要代码行的开头或结尾有注释,下面的代码应该能正常工作。
不过,要记住,文档字符串(docstrings)可以在代码行的中间开始或结束。
另外,你还需要处理三重单引号的情况,以及那些赋值给变量的文档字符串,它们其实并不是注释。
这样说是不是让你更接近答案了呢?
def count_loc(infile):
skipping_comments = False
loc = 0
for line in infile:
# Skip one-liners
if line.strip().startswith("#"): continue
# Toggle multi-line comment finder: on and off
if line.strip().startswith('"""'):
skipping_comments = not skipping_comments
if line.strip().endswith('"""'):
skipping_comments = not skipping_comments
continue
if skipping_comments: continue
print line,
2
while True
是一个无限循环。这意味着它会一直不停地运行,直到你手动停止它。你需要在完成某些操作后使用 break
来跳出这个循环。
4
你没有提供一个退出递归循环的路径。加一个返回语句就可以解决这个问题。
(...)
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
return find_comment(infile, line)
else:
line = infile.readline()