2011-11-01 79 views
0

每当我尝试运行此代码:如何将文件中的行转换为浮动/ INT在Python

#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”,所以它应该输出成功,但我无法越过这个错误。

+0

此代码试图执行什么操作? –

回答

1

我不知道你的代码,但错误信息表明您的文件中有一个空行,你想将其转换为int。例如,很多文本文件末尾都有空行。

我建议首先将其转换之前检查一下线路:

line = ... 
line = line.strip() # strip whitespace 
if line: # only go on if the line was not blank 
    line_value = int(line) 
1

你正在阅读一个空行,python不喜欢这样。您应该检查空白行。

line_value = f.readline(x).strip() 
if len(line_value) > 0: 
    line_value = int(line_value) 
    ... 
+3

'if line:'是写pythonic的一种方式,而不是'len'。 –

1

你必须与变量,长度和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)