总结:
编写一个程序来处理“pc_woodchuck.txt”的内容, 逐行。它在当前工作目录中创建一个名为 “pc_woodchuck.tmp”,其内容与“pc_woodchuck.txt”相同,只是删除了所有元音(不区分大小写)。最后显示读了多少字,写了多少字。
使用以下行创建一个文本文件 (pc_woodchuck.txt) 以获得相同的结果:
Hoeveel hout kan een houthakker hakken
还没有看到 houthakker hout kan hakken?
Hij kan hakken zoveel als hij kan hakken
En hij hakt zoveel als een houthakker kan hakken
Als een houthakker hout kan hakken。
到目前为止的尝试:
from os.path import join
from os import getcwd
def removeVowels( line ):
newline = ""
for c in line:
if c not in "aeiouAEIOU":
newline += c
return newline
inputname = join( getcwd(), "pc_woodchuck.txt" )
outputname = join( getcwd(), "pc_woodchuck.tmp" ) # This will be the copy of the
# textfile at 'inputname' without
# vowels (pc_woodchuck.tmp).
fpi = open( inputname )
fpo = open( outputname, "w" )
countread = 0
countwrite = 0
while True:
line = fpi.readline()
if line == "":
break
countread += len( line )
line = removeVowels( line )
countwrite += len( line )
fpo.write( line )
fpi.close()
fpo.close()
print( "Read:", countread )
print( "Wrote:", countwrite )
到目前为止的输出:
Read: 201
Wrote: 2 # But there must be more than two vowels!
问题:
我做错了什么?结果 'Wrote: 2' 显然不对...
请您参考如下方法:
return newline在for循环中,所以函数return在第一个循环中,所以只有一个字母。
我认为应该是:
def removeVowels( line ):
newline = ""
for c in line:
if c not in "aeiouAEIOU":
newline += c
return newline
