1

每当我尝试运行此代码时:

    #Open file
    f = open("i.txt", "r")
    line = 1

    #Detect start point
    def findstart( x ):
        length = 0
        epsilon = 7
        a = 3
        line_value = int(f.readline(x))
        if line_value == a:
            length = length + 1
            x = x + 1
            findend(x)
        elif line_value == epsilon:
            x = x + 2
            findstart(x)
        else:
            x = x + 1
            findstart(x)

    #Detect end point
    def findend(x):
        line_value = int(f.readline(x))
        if line_value == a:
            length = length + 1
            return ("Accept", length)
        elif line_value == epsilon:
            x = x + 2
            length = length + 2
            findend(x)
        else:
            x = x + 1
            length = length + 1
            findend(x)

    findstart(line)

我得到这个错误代码:

    Traceback (most recent call last):
  File "C:\Users\Brandon\Desktop\DetectSequences.py", line 39, in <module>
    findstart(line)
  File "C:\Users\Brandon\Desktop\DetectSequences.py", line 16, in findstart
    findend(x)
  File "C:\Users\Brandon\Desktop\DetectSequences.py", line 26, in findend
    line_value = int(f.readline(x))
    ValueError: invalid literal for int() with base 10: ''

谁能帮我找出问题所在?在我看来,它正在尝试读取一个空单元格,但我不知道为什么会这样。我正在扫描的文件目前只有两行,每行读数为“3”,所以它应该输出成功,但我无法克服这个错误。

4

3 回答 3

2

我不确定您的代码,但错误消息表明您的文件中有一个空行,您正在尝试将其转换为int. 例如,很多文本文件的末尾都有一个空行。

我建议在转换之前先检查您的线路:

line = ...
line = line.strip() # strip whitespace
if line: # only go on if the line was not blank
    line_value = int(line)
于 2011-11-01T23:48:54.887 回答
1

您的变量 a、长度和 epsilon 存在范围问题。您在 findstart 中定义它,但尝试在 findend 中访问它。

此外,传递给 readline 的变量 x 并没有按照您的想法进行。Readline 总是返回文件中的下一行,传递给它的变量是该行长度的可选提示,而不是应该读取哪一行。要对特定行进行操作,请先将整个文件读入列表:

# Read lines from file
with open("i.txt", "r") as f:
    # Read lines and remove newline at the end of each line
    lines = [l.strip() for l in f.readlines()]

    # Remove the blank lines
    lines = filter(lambda l: l, lines)

EPSILON = 7
A = 3
length = 0

#Detect start point
def findstart( x ):
    global length

    length = 0

    line_value = int(lines[x])
    if line_value == A:
        length += 1
        x += 1
        findend(x)
    elif line_value == EPSILON:
        x += 2
        findstart(x)
    else:
        x += 1
        findstart(x)

#Detect end point
def findend(x):
    global length

    line_value = int(lines[x])
    if line_value == A:
        length += 1
        return ("Accept", length)
    elif line_value == EPSILON:
        x += 2
        length += 2
        findend(x)
    else:
        x += 1
        length += 1
        findend(x)

findstart(0)
于 2011-11-02T00:09:29.633 回答
1

您正在阅读一个空白行,而 python 不喜欢那样。您可能应该检查空行。

line_value = f.readline(x).strip()
if len(line_value) > 0:
    line_value = int(line_value)
    ...
于 2011-11-01T23:48:32.567 回答