到目前为止,我有这个:
def mostFrequentLetter(s):
s1 = sorted(s)
s1 = s.lower()
for x in s1:
if s1.isAlpha == True:
from collections import Counter
def mostFrequentLetter(s):
mc = Counter(c for c in s.lower() if c.isalpha()).most_common()
return ''.join(sorted(c[0] for c in mc if c[1] == mc[0][1]))
示例:
>>> mostFrequentLetter("ZgVhyaBbv")
'bv'
>>> mostFrequentLetter("aaabbcc????")
'a'
n
个字母这将会提供字符串s
中出现频率最高的n
个字母,并按照字母表顺序进行排序:
from collections import Counter
def mostFrequentLetter(s, n=1):
ctr = Counter(c for c in s.lower() if c.isalpha())
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
例子:
>>> mostFrequentLetter('aabbccadef?!', n=1)
'a'
>>> mostFrequentLetter('aabbccadef?!', n=3)
'abc'
c for c in s.lower() if c.isalpha()
This converts string s
to lower case and then just the letters from that string.
ctr = Counter(c for c in s.lower() if c.isalpha())
This creates a Counter instance for those letters. We will use the method most_common
to select the most common letters. To get the three most common letters, for example, we can use:
>>> data.most_common(3)
[('a', 3), ('c', 2), ('b', 2)]
In our case, we are not interested in the counts, only the letters, so we have to manipulate this output.
x[0] for x in ctr.most_common(n)
This selects the n
most common letters.
sorted(x[0] for x in ctr.most_common(n))
This sorts alphabetically the n
most common letters.
return ''.join(sorted(x[0] for x in ctr.most_common(n)))
This joins most common letters back into a string and returns them.
如果不能使用 collections.Counter
,则尝试以下方法:
def mostFrequentLetter(s):
d = {}
for c in s.lower():
d[c] = d.get(c, 0) + 1
mx = max(dict_values())
return sorted(c for c, v in d.items() if v == mx)
def mostFrequentLetter(s):
s1 = s.lower()
new = set(s1)
mod={}
for item in new:
if item.isalpha():
mod[item]=s1.count(item)
frequent = sorted (mod,key = mod.get)
return list(reversed(frequent))
Counter
的版本。 - John1024