我有一个未标准化的名称列表,例如:
'one Bull', 'A Horse', 'Horse', 'Dog', 'Black dog', 'Brown dog', 'Bird', 'I'm a horse', 'I'm not a dog'
我想要获取的是最常见值的列表,如果数据干净,使用 SQL 会很容易,但没有标准化数据,我不知道如何获得类似的列表,如下所示:
'Dog' - 4
'Horse' - 3
'A' - 3
...
我发现 Python 有一个 Counter 模块,可能会有所帮助,但它会将字符串计为一个 "One bull"
,而不是计为单词的混合 "One ”,“公牛”。
也许之前分割过字符串?
最佳答案
您可以将列表中的项目拆分为单独的单词,并使用 str.capitalize
将首字母转换为大写。在用 collections.Counter
计数之前:
from collections import Counter
lst= ['one Bull', 'A Horse', 'Horse', 'Dog', 'Black dog', 'Brown dog', 'Bird', 'I\'m a horse', 'I\'m not a dog']
c = Counter(i.capitalize() for x in lst for i in x.split())
print(c)
# Counter({'Dog': 4, 'Horse': 3, 'A': 3, "I'm": 2, 'Black': 1, 'Brown': 1, 'Bull': 1, 'Not': 1, 'One': 1, 'Bird': 1})
然后使用计数器对象的most_common
获取所需数量的最常见元素:
print(c.most_common(3))
# [('Dog', 4), ('Horse', 3), ('A', 3)]
关于python - 获取列表中出现频率最高的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505290/