[英]Python 3.0 - How do I output which character is counted the most?
因此,我能夠創建一個程序來計算我計算機上的文本文件中的元音(特別是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()
如果要顯示哪一個出現次數最多,則必須保留每個元音的計數,而不是像做的那樣僅保留1個總數。
保留3個獨立的計數器(您關心的3個元音中的每個元音),然后將它們加起來即可得出總數;或者,如果您想找出哪個元音出現得最多,您可以簡單地比較3個計數器來找出。
嘗試使用正則表達式; 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()
你可以這樣做:
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())]))
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']
讓vowels = 'eio'
,然后
{ i: contents.count(i) for i in vowels }
對於vowels
每一項,計算contents
中出現的次數,並將其添加為結果字典的一部分(請注意,在理解上用大括號括起來)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.