2012-03-29 37 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

相关问题