程序输入是一个字符串。我想要从这个字符串中找到最常见的字母。如果有多个字母具有相同的频率,我将返回拉丁字母表中第一个字母
代码:
def most_Wanted(text="Hello Oman"):
lst = [x for x in text.replace(" ","").lower() if x.isalpha]
count = {}
for letter in lst:
if letter in count:
count[letter] += 1
else:
count[letter] = 1
count = list(count.items())
sorted(count, key=lambda x: (-x[1],x[0]))
print(count[0][0])
预期:
l #though o and l appear 3 times, l is before o in the latin alphabet
输出:
h #there seems to be an error in the sorting as the first pair of tuples in the list always seems to be the first letter of the text?
任何关于美化代码的建议都很好,尽管我宁愿现在不使用模块,这样我就可以学习核心Python。谢谢:)
最佳答案
主要问题是 sorted
返回一个新列表,它不是就地的。
您应该重新分配其返回值,或使用.sort()
:
count = sorted(count, key=lambda x: (-x[1],x[0]))
或
count.sort(key=lambda x: (-x[1],x[0]))
线路也有问题
lst = [x for x in text.replace(" ","").lower() if x.isalpha]
if x.isalpha
总是返回 True
因为它只是引用函数而不是实际调用它。应改为
lst = [x for x in text.replace(" ","").lower() if x.isalpha()]
关于python - 找到单词中最常见的字母;按字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845635/