计算文件中的元音和辅音(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)

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

原文由 PyPunk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
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)

原文由 cs95 发布,翻译遵循 CC BY-SA 3.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)

原文由 Ishar Sk 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题