我需要制作一个程序来读取文本文件并打印出有多少个元音和辅音。我制作了一个文本文件进行测试,其中唯一的内容是“这是一个测试”。但是输出总是:
输入要检查的文件: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() 将文件中的所有内容转换为小写时出现错误……
原文由 PyPunk 发布,翻译遵循 CC BY-SA 4.0 许可协议
set("A E I O U a e i o u")
将导致{' ', 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}
。如果您注意到,还会考虑空间。您需要删除字母之间的空格。infile.read().split()
将根据空格进行拆分,以便您获得 _单词列表_。然后继续迭代 _单词_,并尝试在 单词 和 字母 之间进行成员资格比较。这不适合你。你不需要迭代两次。一次就够了。
这是您的代码的清理版本。
作为改进,请考虑使用
collections.Counter
。它会为您计数,而您只需将计数相加即可。