为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我只得到“0”输出?

为什么我只得到“0”输出?

白猪掌柜的 2024-01-27 16:05:19
我试图搜索文本文件并确定文本文件中有多少行、元音、辅音和数值/字符。我的元音、辅音和数字输出值似乎没有正确计算。线路输出总计已正确计算。ein = input("Please enter file name: ")vowels = set("AEIOUaeoiu")cons = set("BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwvyz")num = set("1234567890")count = 0Vcount = 0Ccount = 0Ncount = 0with open(ein) as ein_handle:    for line in ein_handle:        count += 1    for line in ein_handle:        if line in vowels:            Vcount += 1        elif line in cons:            Ccount += 1        elif line in num:            Ncount += 1print("the file has",count,"lines.")print("the file has",Vcount,"vowels.")print("the file has",Ccount,"consonants.")print("the file has",Ncount,"numerical characters.")
查看完整描述

2 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

第二个循环应该针对给定行中的每个字符。


试试这个:


ein = input("Please enter file name: ")

vowels = set("AEIOUaeoiu")

cons = set("BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwvyz")

num = set("1234567890")

count = 0

Vcount = 0

Ccount = 0

Ncount = 0

with open(ein) as ein_handle:

    for line in ein_handle:

        count += 1

        for letter in line:

            if letter in vowels:

                Vcount += 1

            elif letter in cons:

                Ccount += 1

            elif letter in num:

                Ncount += 1

print("the file has", count, "lines.")

print("the file has", Vcount, "vowels.")

print("the file has", Ccount, "consonants.")

print("the file has", Ncount, "numerical characters.")


另外,在第二个循环内得到 0 (而不是行数)的主要原因是因为当第一个循环执行时,它会在每次迭代时更新读取偏移位置,直到它结束。因此,当第二个循环开始时,它从文件末尾开始,无法读取任何内容。


查看完整回答
反对 回复 2024-01-27
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

这是另一种方法:


import os

d,_ = os.path.split(__file__)


ein = input("Please enter file name: ")

vowels = "aeoiu"

cons = "bcdfghjklmnpqrstvwvyz"

num = "1234567890"

Vcount = 0

Ccount = 0

Ncount = 0

with open(d+"\\" + ein) as ein_handle:

    lines = ein_handle.readlines()

    for line in lines:

        line = line.lower()

        for v in vowels:

            tmp = line

            while v in tmp:

                Vcount += 1

                tmp = tmp[tmp.find(v)+1:]

        for c in cons:

            tmp = line

            while c in tmp:

                Ccount += 1

                tmp = tmp[tmp.find(c)+1:]

        for n in num:

            tmp = line

            while n in tmp:

                Ncount += 1

                tmp = tmp[tmp.find(n)+1:]

print("the file has",len(lines),"lines.")

print("the file has",Vcount,"vowels.")

print("the file has",Ccount,"consonants.")

print("the file has",Ncount,"numerical characters.")


查看完整回答
反对 回复 2024-01-27
  • 2 回答
  • 0 关注
  • 48 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信