我需要做一个程序,将读取一个文本文件,并打印出有多少元音和辅音。我做了一个文本文件来测试,其中唯一的东西是“这是一个测试”。但是输出总是:
输入要检查的文件: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()将文件中的所有内容转换为小写时,我得到了一个错误。。。。。
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
。它为你计数,你只需把计数加起来。如果输入文件
fileName
包含不同于元音和辅音的字符,例如. , \n
,则解决方案是使用re.split()
和re.sub()
而不是方法str.split()
:表达式
re.sub("[.,\n+]", " ", infile.read())
将用空白替换字符. , \n
。然后expresionre.split("\s+", re.sub("[.,\n+]", " ", infile.read())
将拆分“clean”infile.read()
文本,并使用多个空格字符重复中的一个作为条件相关问题 更多 >
编程相关推荐