“remove元音”函数只打印“readline()”的第一个字母,我做错了什么?

2024-04-29 10:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

总结:

写一个程序来处理“pc\u woodchuck.txt”的内容 一行一行。它在当前工作目录中创建一个名为 “pc\u woodchuck.tmp”,它的内容与“pc\u woodchuck.txt”相同,只是所有元音都被删除了(不区分大小写)。最后,显示你读了多少个字符,写了多少个字符

创建包含以下行的文本文件(pc\u woodchuck.txt)以获得相同的结果:

Hoeveel hout kan een houthakker hakken Hoeveel hout kan een houthakker hakken
你是说你是谁?
Hij kan hakken zoveel als你好,你好
你知道吗?你知道吗 我也不知道

迄今为止的尝试:

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!

问题:

我做错什么了?结果“写道:2”显然不对


Tags: txtlinenewlinetmpjoinpcgetcwdfpi
1条回答
网友
1楼 · 发布于 2024-04-29 10:42:26

return newline在for循环中,因此函数在第一个循环中返回,这就是为什么只有一个字母

我想应该是:

def removeVowels( line ):
newline = ""
for c in line:
    if c not in "aeiouAEIOU":
        newline += c
return newline

相关问题 更多 >