Python 如何输出最常用的字母?
此代码输出字母以及使用了多少次,但是如何修改它以查找和打印使用最多的字母 您只需按值对字母进行排序,然后写入排序数组的最后一个成员:Python 如何输出最常用的字母?,python,python-3.x,Python,Python 3.x,此代码输出字母以及使用了多少次,但是如何修改它以查找和打印使用最多的字母 您只需按值对字母进行排序,然后写入排序数组的最后一个成员: def main(): x = {} for word in sentence: x[word] = sentence.count(word) for letter in sorted(x): print (letter + ': ' + str(x[letter])) sentence=input("
def main():
x = {}
for word in sentence:
x[word] = sentence.count(word)
for letter in sorted(x):
print (letter + ': ' + str(x[letter]))
sentence=input("Enter a sentence: ")
main()
输入/输出示例:
def main():
x = {}
for word in sentence:
x[word] = sentence.count(word)
sorted_letters = sorted(x, key=lambda v: x[v])
for letter in sorted_letters:
print (letter + ': ' + str(x[letter]))
print('Most used letter =', sorted_letters[-1])
sentence=input("Enter a sentence: ")
main()
也许您希望使用集合中的“defaultdict()” 它所做的是,即使在按键调用时字典中没有键, 它不会导致任何错误
Enter a sentence: Hello World!
H: 1
e: 1
: 1
W: 1
r: 1
d: 1
!: 1
o: 2
l: 3
Most used letter = l
因此,要从dict
x
中查找最大使用的单词,可以使用运算符-
import collections
s = "This is a random sequence of text"
d = collections.defaultdict(int)
for c in s:
if c != " ":
d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])
但这只会给你n个单词中的一个单词具有相等的值,即max value如果你正在寻找一个易于阅读的解决方案,接近你想要实现的,可以实现这个技巧
import operator
print max(x.iteritems(), key=operator.itemgetter(1))[0]
基本上,它返回任何出现次数最多的字母。请注意,这将考虑多个字母出现次数相同的情况
编辑
还要注意,我添加了if-word!=“:”/>代码>因为您的初始代码将把一个空间当作一个词,这可能不是您想要的。p> 如果您将代码修改为使用,您可以利用计数器。最常见的导入统计信息和统计信息。模式(句子)
我尝试过,但我对该功能不太熟练。有什么想法吗?对于OP来说,这感觉像是一个很糟糕的重复。即使问题标题相似,也不意味着它们是重复的……如果多个字母的出现次数相同怎么办?@scharette这是edge case,OP需要指定需要发生什么。
def main():
x = {}
for word in sentence:
if word != " ":
x[word] = sentence.count(word)
maximum_occurrences = max(x.values())
for letter,occurrences in x.items():
if occurrences == maximum_occurrences:
print("Max value found, the letter "+ letter + " was found " + str(occurrences)+ " times.")
sentence=input("Enter a sentence: ")
main()
>>>> Enter a sentence: This is simply a test
>>>> Max value found, the letter s was found 4 times.