2012-09-24 44 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'更有意义。 –