如何计算文本文件中元音和辅音的数量?

2024-07-05 14:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试着正确地计算辅音和辅音的数量。我还有其他需要做的部分。在

# Home work 4
from string import punctuation

fname = raw_input("Enter name of the file: ")
fvar = open(fname, "r")
punctuationList = "!#$%&'(),.:;?"
numLines = 0
numWords = 0
numChars = 0
numPunc = 0
numVowl = 0
numCons = 0


if line in "aeiou":
    numVowl = + 1
else:
    numCons += 1

for line in fvar:
    wordsList = line.split()
    numLines += 1
    numWords += len(wordsList)
    numChars += len(line)
for punctuation in punctuationList:
    numPunc += 1


print "Lines %d" % numLines
print "Words %d" % numWords
print "The amount of charcters is %d" % numChars
print "The amount of punctuation is %d" % numPunc
print "The amount of vowls is %d" % numVowl
print "The amount of consonants is %d" % numCons

Tags: oftheinislineamountprintpunctuation
3条回答

你可以试试这个:

f = [i.strip('\n').split() for i in open('file.txt')]
new_lines = [[sum(b in 'bcdfghjklmnpqrstvwxyz' for b in i), sum(b in "aeiou" for b in i)] for i in f]
total_consonants = sum(a for a, b in new_lines)
total_vowels = sum(b for a, b in new_lines)

你需要遍历行中的所有字符,测试它们是元音、辅音还是标点符号。在

for line in fvar:
    wordsList = line.split()
    numLines += 1
    numWords += len(wordsList)
    numChars += len(line)
    for char in line:
        if char in 'aeiou':
            numVowl += 1
        elif char in 'bcdfghjklmnpqrstvwxyz'
            numCons += 1
        else:
            numPunc += 1

我会写一个函数,当给定一个字符串时,它返回一个3元组的计数。在

import string

def count_helper(s) -> ("vowel count", "consonant count", "punctuation count"):
    vowels = set('aeiou')
    consonants = set(string.ascii_lowercase).difference(vowels)
    # you could also do set('bcdfghjklmnpqrstvwxyz'), but I recommend this approach
    # because it's more obviously correct (you can't possibly typo and miss a letter)
    c_vowel = c_consonant = c_punctuation = 0
    for ch in s:
        if ch in vowels: c_vowel += 1
        elif ch in consonants: c_consonant += 1
        else: c_punctuation += 1
    return (c_vowel, c_consonant, c_punctuation)

然后在遍历文件时,将每一行传递给count_helper。在

^{pr2}$

相关问题 更多 >