我是python(第2天)的新手,正在解决一个问题,要求我编写一个读取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...")