我是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...")
注意:您實際上無故打開文件兩次。由於'for'循環,你只會看文件的最後一行。 – interjay
謝謝,我擺脫了額外的開放 – scrayon
@MatthewLiem你在哪裏放了'raw_input(「按回車關閉這個窗口......」)? –