Python - 请求输入,从文件中提取数据

时间:2012-09-24 15:59:34

标签: python python-2.7

我是python(第二天)的新手并且正在处理一个问题,要求我编写一个读取ASCII文件的程序(要求输入文件名),检查它是否超过 两个单词并打印出屏幕上文件的两个第一个单词。

它有点模糊,但我将假设文件全部是str,由空格分隔。

离。

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 *这是我当前的代码,仍在尝试在

之后打开cmd窗口
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...")

2 个答案:

答案 0 :(得分:1)

该代码应写为:

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的使用(表示“其他如果”)。

答案 1 :(得分: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'