2012-03-29 39 views
-1
fileName = raw_input("Enter the filename: ") 
n = input("Enter the line you want to look: ") 
f = open(fileName,'r') 
numbers = [] 

for line in f: 
    sentenceInLine = line.split('\n') 
    for word in sentenceInLine: 
      if word != '': 
       numbers.append(word) 
print numbers 
print len(numbers) 
print numbers[n-1] 

if n == 0: 
    print "There is no 0 line" 
    break 
+0

原來的問題要求。 – Zfrd 2012-03-29 20:12:23

回答

2

我想你錯過分裂sentenceInLinesentenceInLine.split(' ')

2

你遍歷每一行,然後你根據'\n'分割線。 \ n是換行符。那會混淆你的邏輯。

1

因此,你試圖做的事情有點令人困惑,但你應該在用戶輸入n的值後檢查n。不在最後。

你可能想也搭上那裏的文件不能被發現,我認爲這是你需要什麼異常:當用戶輸入n = 0時,該程序退出

fileName = raw_input("Enter the filename: ") 
n = input("Enter the line you want to look: ") 
if n == 0: 
    print "There is no 0 line" 
    sys.exit(); 

try: 
    f = open(fileName,'r') 
except IOError: 
    print "Could not find file" 
    sys.exit() 
+0

感謝您的幫助,問題解決了:) – Zfrd 2012-03-29 21:48:22

+0

@Zfrd如果這回答了您的問題,您是否可以接受它作爲正確的答案。謝謝 – Jtello 2012-03-30 16:00:54

相關問題