2012-09-24 41 views
0

我是python(2nd)day的新手,正在研究一個問題,要求我編寫一個讀取ASCII文件的程序(要求輸入文件名),檢查它是否存在具有多於 兩個單詞並在屏幕上打印文件的兩個第一個單詞。Python - 詢問輸入,從文件中提取數據

它有點含糊,但我會假設文件是​​所有str,由空格分隔。

ex。

text1 text2 text text text 

到目前爲止,我有:

name = (raw_input("Please enter the name of the file: ")) 
f=open(name) 
with codecs.open(name, encoding='utf-8') as f: 
    for line in f: 
     line = line.lstrip(BOM) 
words=line.split() 
print words 
if len(words) > 2: 
    print 'There are more than two words' 
    firsttow = words[:2] 
    print firstrow 

我有寫else語句的問題,我想有,

if len(words) > 2: 
    print 'There are more than two words' 
    firsttow = words[:2] 
print firstrow 
else: 
if len(words) <2: 
     print 'There are under 2 words, no words will be shown' 

如何來加,是否有任何其他如何改善我的代碼這個問題? 我真的很感激幫助提前

感謝

*編輯:感謝所有幫助,最後的問題,我是當我運行.py文件,我希望能夠看到之前的結果cmd窗口關閉。

添加:raw_input("Press return to close this window...")不起作用,它馬上關閉。有任何想法嗎?

EDIT2 *這是我當前的代碼,仍然在努力之後

import codecs 
BOM = codecs.BOM_UTF8.decode('utf8') 
name = (raw_input("Please enter the name of the file: ")) 

with codecs.open(name, encoding='utf-8') as f: 
    words=[]   #define words here 
    for line in f: 
     line = line.lstrip(BOM) 
     words.extend(line.split())  #append words from each line to words 

if len(words) > 2: 
    print 'There are more than two words' 
    firstrow = words[:2] 
    print firstrow    #indentation problem here 
elif len(words) <2:     #use if 
    print 'There are under 2 words, no words will be shown' 

raw_input("Press return to close this window...") 
+0

注意:您實際上無故打開文件兩次。由於'for'循環,你只會看文件的最後一行。 – interjay

+0

謝謝,我擺脫了額外的開放 – scrayon

+0

@MatthewLiem你在哪裏放了'raw_input(「按回車關閉這個窗口......」)? –

回答

1

該代碼在具有打開cmd窗口工作應該寫成:

if len(words) > 2: 
    print 'There are more than two words' 
    firsttow = words[:2] 
    print firstrow 
elif len(words) <2: 
    print 'There are under 2 words, no words will be shown' 

注意壓痕和使用elif(意思是「else if」)。

+0

AHHH多數民衆贊成在這個問題上,這是我的縮進..堅持爲什麼我的其他或ELIF永遠不會工作。謝謝!! – scrayon

0
with codecs.open(name, encoding='utf-8') as f: 
    words=[]   #define words here 
    for line in f: 
     line = line.lstrip(BOM) 
     words.extend(line.split())  #append words from each line to words  

if len(words) > 2: 
    print 'There are more than two words' 
    firsttow = words[:2] 
    print firstrow    #indentation problem here 
if len(words) <2:     #use if 
    print 'There are under 2 words, no words will be shown' 
+0

謝謝,是否有一個原因,你使用另一個,而不是其他? – scrayon

+0

@MatthewLiem都能正常工作,但在這裏使用'elif'更有意義。 –