1

因此,我能够创建一个程序来计算计算机上的文本文件中元音(特别是 eio)的数量。但是,我一生都无法弄清楚如何显示哪一个出现最多。我以为我会说类似的话

for ch in 'i':
    return numvowel?

我只是不太确定步骤是什么。我基本上希望它最后输出“字母 i,在文本文件中出现次数最多”

def vowelCounter():
    inFile = open('file.txt', 'r')
    contents = inFile.read()

    # variable to store total number of vowels
    numVowel = 0

    # This counts the total number of occurrences of vowels o e i.
    for ch in contents:
        if ch in 'i':
            numVowel = numVowel + 1
        if ch in 'e':
            numVowel = numVowel + 1    
        if ch in 'o':
            numVowel = numVowel + 1

    print('file.txt has', numVowel, 'vowel occurences total')
    inFile.close()

vowelCounter()
4

5 回答 5

3

如果你想显示哪个出现次数最多,你必须记录每个元音的计数,而不是像你所做的那样只计算 1 个总计数。

保留 3 个单独的计数器(一个用于您关心的 3 个元音中的每一个),然后您可以通过将它们相加来获得总数,或者如果您想找出哪个元音出现的次数最多,您可以简单地比较 3 个计数器来找出答案。

于 2016-02-14T19:42:30.187 回答
1

尝试使用正则表达式; https://docs.python.org/3.5/library/re.html#regular-expression-objects

import re

def vowelCounter():

    with open('file.txt', 'r') as inFile:

        content = inFile.read()

        o_count = len(re.findall('o',content))
        e_count = len(re.findall('e',content))
        i_count = len(re.findall('i',content))

        # Note, if you want this to be case-insensitive,
        # then add the addition argument re.I to each findall function

        print("O's: {0}, E's:{1}, I's:{2}".format(o_count,e_count,i_count))

vowelCounter()
于 2016-02-14T19:53:01.927 回答
1

你可以这样做:

vowels = {} # dictionary of counters, indexed by vowels

for ch in contents:
    if ch in ['i', 'e', 'o']:
        # If 'ch' is a new vowel, create a new mapping for it with the value 1
        # otherwise increment its counter by 1
        vowels[ch] = vowels.get(ch, 0) + 1

print("'{}' occured the most."
    .format(*[k for k, v in vowels.items() if v == max(vowels.values())]))
于 2016-02-14T19:53:18.450 回答
1

Python声称“包含电池”,这是一个经典案例。这个类collections.Counter几乎做到了这一点。

from collections import Counter

with open('file.txt') as file_
    counter = Counter(file_.read())

print 'Count of e: %s' % counter['e']
print 'Count of i: %s' % counter['i']
print 'Count of o: %s' % counter['o']
于 2016-02-14T20:09:19.863 回答
0

vowels = 'eio'那么让

{ i: contents.count(i) for i in vowels }

对于vowelscount 中的每个项目,计算出现的次数contents并将其添加为结果字典的一部分(注意在理解上的环绕大括号)。

于 2016-02-14T20:13:38.137 回答