【发布时间】:2018-01-14 01:56:44
【问题描述】:
我需要编写一个程序来读取文本文件并打印有多少元音和辅音。我制作了一个文本文件进行测试,其中唯一的内容是“这是一个测试”。但是输出它总是:
输入要检查的文件: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() 将文件中的所有内容转换为小写时出现错误... ..
【问题讨论】:
-
因为你也算空格??
标签: python python-3.x for-loop lowercase