计算文件中的元音和辅音(Python)

2024-06-01 06:50:26 发布

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

我需要做一个程序,将读取一个文本文件,并打印出有多少元音和辅音。我做了一个文本文件来测试,其中唯一的东西是“这是一个测试”。但是输出总是:

输入要检查的文件:test.txt

元音的数目是:1

辅音的数目是:0

fileName = input("Enter the file to check: ").strip()

infile = open(fileName, "r")


vowels = set("A E I O U a e i o u")
cons = set("b c d f g h j k l m n p q r s t v w x y z B C D F G H J K L M N P Q R S T V W X Y Z")

text = infile.read().split()


countV = 0
for V in text:
    if V in vowels:
        countV += 1

countC = 0
for C in text:
    if C in cons:
        countC += 1

print("The number of Vowels is: ",countV,"\nThe number of consonants is: ",countC)

如果有更好的方法来输入元音和cons的值,我也想知道,因为当我试图使用.lower()将文件中的所有内容转换为小写时,我得到了一个错误。。。。。


Tags: 文件textinforfilenameinfile文本文件元音
2条回答
  1. set("A E I O U a e i o u")将导致{' ', 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}。如果你会注意到的话,空间也会被考虑进去。你需要去掉字母之间的空格。

  2. infile.read().split()将基于空格进行拆分,这样您将得到一个单词列表。然后继续迭代单词,并尝试比较单词字母之间的成员关系。这对你不合适。

  3. 你不需要重复两次。一次就够了。


这是你的代码的清理版本。

vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")

countV = 0
countC = 0
for c in infile.read():
    if c in vowels:
        countV += 1
    elif c in cons:
        countC += 1

作为改进,考虑使用collections.Counter。它为你计数,你只需把计数加起来。

import collections
c = collections.Counter(infile.read())

countV = sum(c[k] for k in c if k in vowels)
countC = sum(c[k] for k in c if k in cons)

如果输入文件fileName包含不同于元音和辅音的字符,例如. , \n,则解决方案是使用re.split()re.sub()而不是方法str.split()

import re
text = re.split("\s+", re.sub("[.,\n+]", " ", infile.read()))

表达式re.sub("[.,\n+]", " ", infile.read())将用空白替换字符. , \n。然后expresionre.split("\s+", re.sub("[.,\n+]", " ", infile.read())将拆分“clean”infile.read()文本,并使用多个空格字符重复中的一个作为条件

相关问题 更多 >