繁体   English   中英

相同的Python代码为同一输入字符串返回不同的结果

[英]Same Python code returns different results for same input string

下面的代码应该以下面的格式返回TEXT字符串中最常见的字母:

  • 总是小写的
  • 忽略标点符号和空格
  • 在诸如“One”之类的单词的情况下 - 其中没有2个字母相同 - 返回字母表中的第一个字母

每次我使用相同的字符串运行代码时,例如“One”,结果会循环显示字母......但奇怪的是,只有第三次尝试(在“One”示例中)。

text=input('Insert String: ')
def mwl(text):
    from string import punctuation
    from collections import Counter
    for l in punctuation:
        if l in text:
            text = text.replace(l,'')
    text = text.lower()
    text=''.join(text.split())
    text= sorted(text)
    collist=Counter(text).most_common(1)
    print(collist[0][0])
mwl(text)   

Counter使用字典:

>>> Counter('one')
Counter({'e': 1, 'o': 1, 'n': 1})

字典不是有序的,因此是行为。

您可以使用OrderedDict替换以下两行来获得所需的输出:

text= sorted(text)
collist=Counter(text).most_common(1)

有:

collist = OrderedDict([(i,text.count(i)) for i in text])
collist = sorted(collist.items(), key=lambda x:x[1], reverse=True)

您还需要为此导入OrderedDict

演示:

>>> from collections import Counter, OrderedDict
>>> text = 'One'
>>> collist = OrderedDict([(i,text.count(i)) for i in text])
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
O  
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
O    # it will always return O
>>> text = 'hello'
>>> collist = OrderedDict([(i,text.count(i)) for i in text])
>>> print(sorted(collist.items(), key=lambda x:x[1], reverse=True)[0][0])
l    # l returned because it is most frequent

这也可以在没有CounterOrderedDict情况下完成:

In [1]: s = 'Find the most common letter in THIS sentence!'
In [2]: letters = [letter.lower() for letter in s if letter.isalpha()]
In [3]: max(set(letters), key=letters.count)
Out[3]: 'e'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM