-1

我不明白为什么这行不通。我正在对传递给函数的字符串执行 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:
        (...)
4

5 回答 5

4

您没有提供并退出递归循环的路径。return 语句应该可以解决问题。

    (...)
    while True:
        if line.rstrip().endswith('"""'):
            line = infile.readline()
            return find_comment(infile, line)
        else:
            line = infile.readline()
于 2009-05-30T06:57:19.507 回答
2

while True是一个无限循环。完成后,您需break要这样做。

于 2009-05-30T06:49:50.253 回答
1
not line_t.startswith('"""') or not line_t.startswith('#')

无论字符串 line_t 表示什么,此表达式的计算结果都为 True。你想要'and'而不是'or'吗?你的问题我不清楚。

于 2009-05-30T06:32:59.960 回答
1
if not line_t.startswith('"""') or not line_t.startswith('#'):

if将始终得到满足——要么该行不以 开头""",要么不以#(或两者)开头。你可能打算and在你使用的地方使用or.

于 2009-05-30T06:37:58.280 回答
1

只要行以注释开头或结尾,下面的代码就可以工作。

但是,请记住,文档字符串可以在一行代码的中间开始或结束。

此外,您需要为三重单引号以及分配给不是真正注释的变量的文档字符串编写代码。

这会让你更接近答案吗?

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,
于 2009-05-30T07:01:10.747 回答