【问题标题】:Counting vowels and consonants in a file (Python)计算文件中的元音和辅音(Python)
【发布时间】: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


【解决方案1】:
  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() 将根据空格进行拆分,以便您获得单词列表。然后您继续迭代 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)

【讨论】:

  • 谢谢@COLDSPEED 这有帮助。我做的略有不同,但摆脱 .split() 并删除空格是一个很大的帮助。我认为这些集合不会重复自己吗?那么这是否意味着它也会计算空格而不是结果显示 0?
  • @EvanH 它计算了一次空格,但它们仍然被计算在内。除非您删除它们,否则您将错误地将空格同时计为元音和字符。
  • @COLDSPEED 知道了。非常感谢您的帮助和快速响应!
  • @EvanH 没问题。作为新用户,您应该知道如果有帮助,您可以mark an answer accepted。这是一种表达感谢的好方法,它也对社区有所帮助。欣赏!
  • @EvanH 要单击答案旁边的灰色复选标记。我知道你明白了,但要注意每个问题只能标记一个答案!
【解决方案2】:

如果输入文件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()) 将拆分“干净”infile.read() 文本,使用更多空白字符的重复作为标准

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多