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

时间:2017-10-05 21:08:05

标签: 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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你可以试试这个:

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)

答案 2 :(得分:0)

我会编写一个函数,在给定字符串时返回你关心的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

counts = {'vowels': 0, 'consonants': 0, 'punctuation': 0}
for line in f:
    v, c, p = count_helper(line)
    counts['vowels'] += v
    counts['consonants'] += c
    counts['punctuation'] += p