2011-11-01 34 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)