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

Counting vowels and consonants in a file (Python)

我需要编写一个程序来读取文本文件并打印出有多少个元音和辅音。我制作了一个文本文件进行测试,其中唯一的内容是 "This is a test"。但是输出总是:

输入要检查的文件: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)

如果有更好的方法来输入元音和缺点的值,我也想知道,因为当我尝试使用 .lower() 将文件中的所有内容转换为小写时出现错误。 ....

  1. set("A E I O U a e i o u") 将导致 {' ', 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}。如果您注意到,space 也被考虑在内。您需要删除字母之间的 spaces。

  2. infile.read().split() 将根据白色 space 进行拆分,因此您会得到一个 单词列表 。然后继续迭代 words,并尝试比较 wordsletters 之间的成员关系.这不适合你。

  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 替换为空格。然后表达式 re.split("\s+", re.sub("[.,\n+]", " ", infile.read()) 将拆分 'clean' infile.read() 文本,使用更多重复的空白字符

作为标准之一
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)