【问题标题】:IndexError reading in comments in source code folderIndexError 读取源代码文件夹中的注释
【发布时间】:2014-06-14 01:21:45
【问题描述】:

我正在编写一个程序来检查我通过列表“队列”传入的文件列表。

我正在尝试逐行浏览文件并仅选择单行注释或多行注释中的文本。 (“//”和“/* */” -> 可能不止一行)。

我不明白为什么我的程序没有按预期进入下一行。如果未满足注释结束指定“终止”,则变量“步进器”将递增。

这几天我一直在进行错误测试和修改,但我不确定为什么这不起作用。

对于草率的代码,我很抱歉。

def main(queue):
    for item in queue:
        with open("output.txt", "a") as out_file:
            out_file.write(str("\t<FILE: " + item.split("\\")[len(item.split()) - 1] + ">"))
            java_file = list(open(item, "r"))
            for line in range(0, len(java_file)):
                for i in range(0, len(java_file[line])):
                    multi_builder = []
                    single_lines = []
                    if (java_file[line][i] == "/" and java_file[line][i + 1] == "/"):
                        single_lines.append(java_file[line][i:])
                    if (java_file[line][i] == "/" and java_file[line][i + 1] == "*"):
                        stepper = 0
                        terminated = False
                        while not terminated:
                            for char in range(0, len(java_file[line + stepper])):
                                if not java_file[line][char].strip() == "":
                                    print (java_file[line][char])
                                    if (java_file[line][char] == "*" and java_file[line][char + 1] == "/"):
                                        if stepper == 0:
                                            multi_builder.append(java_file[line][i:char + 1])
                                        multi_builder.append(java_file[line][:char + 1])
                                        terminated = True
                                    else:
                                        multi_builder.append(java_file[line])
                                        stepper += 1

【问题讨论】:

  • 在问题中包含堆栈跟踪会有所帮助
  • 不清楚你认为问题出在哪里。
  • 此外,我们可能会帮助您找到解决问题的方法,但看起来您正在重新发明轮子。 Regular expressions 专为这类事情而设计。

标签: python file-io documentation indexoutofboundsexception


【解决方案1】:

我不确定您是否对替代方法感兴趣,而不是帮助调试您的方法,但使用 regular expressions 会使这项任务变得更容易:

import re

singleLinePattern = re.compile("//.*$", flags=re.MULTILINE+re.DOTALL)
multiLinePattern = re.compile("/\*.*?\*/", flags=re.MULTILINE+re.DOTALL)

def main(queue):
    for item in queue:
        with open("output.txt", "a") as out_file:
            out_file.write(str("\t<FILE: " + item.split("\\")[len(item.split()) - 1] + ">"))
            with open(item, "r") as f:
                java_file = f.read()
            print "singles:", singleLinePattern.findall(java_file)
            print "multis:", multiLinePattern.findall(java_file)
            # You can write the results to the output file here.

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 2015-03-07
    • 1970-01-01
    • 2011-02-20
    • 2011-02-03
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多