为了对列表中的事物进行计数,python 在其集合模块中提供了一个类似 dict 的 Counter() 类:Doku,它计算 O(n) 中的出现次数并将它们作为字典提供。
from collections import Counter
L1 = ['newnes', 'imprint', 'elsevier', 'corporate', 'drive', 'suite',
'burlington', 'usa', 'linacre', 'jordan', 'hill', 'oxford', 'uk',
'elsevier', 'inc', 'right', 'reserved', 'exception', 'newness', 'uk', ...]
L2 = ['usa', 'uk', 'hill', 'drive', ... ]
c = Counter(L1)
print(c)
输出:
Counter({'elsevier': 2, 'uk': 2, 'newnes': 1, 'imprint': 1, 'corporate': 1,
'drive': 1, 'suite': 1, 'burlington': 1, 'usa': 1, 'linacre': 1,
'jordan': 1, 'hill': 1, 'oxford': 1, 'inc': 1, 'right': 1, 'reserved': 1,
'exception': 1, 'newness': 1, Ellipsis: 1})
它提供了一种方便的方法来将结果排序为元组列表(key, count) 命名为most_common() - 如果您使用第一个,您将获得最常用的单词,您可以将其与列表推导一起使用来修改您的来源列表:
word,_ = c.most_common()[0] # get word mos often used
# inplace modification of L1
L1[:] = [ x if x != word else "#"+word+"#" for x in L1] # use x if not the most used word
L2[:] = [ x if x != word else "#"+word+"#" for x in L2] # else pre-/append #
print(L1)
print(L2)
输出:
['newnes', 'imprint', '#elsevier#', 'corporate', 'drive', 'suite', 'burlington',
'usa', 'linacre', 'jordan', 'hill', 'oxford', 'uk', '#elsevier#', 'inc',
'right', 'reserved', 'exception', 'newness', 'uk', Ellipsis]
['usa', 'uk', 'hill', 'drive', Ellipsis]
Counter 中的项目顺序与原始列表中的顺序相关,L1 中有多个项目,计数为 2 - elsevier 是其中的第一个,因此它也是第一个使用most_common()
编辑 4 条评论:
from collections import Counter
L1 = ['newnes', 'imprint', 'elsevier', 'corporate', 'drive', 'suite',
'burlington', 'usa','imprint', 'linacre', 'jordan', 'hill', 'oxford', 'uk','uk',
'elsevier', 'inc', 'right', 'reserved','imprint', 'exception', 'imprint','newness', 'uk', "..."]
L2 = ['usa', 'uk', 'hill', 'drive', "..."]
c = Counter(L1)
substs = "#*+~-:;=)(/&%$§!"
i = 0
for word,count in c.most_common():
temp = substs[i]*count # use the i-th char as substitute, apply it count times
L1[:] = [ x if x != word else temp+word+temp for x in L1] # use x if not the most used word
L2[:] = [ x if x != word else temp+word+temp for x in L2] # else pre-/append #
i += 1
i = i % len(substs) # wrap around
print(L1)
print(L2)
输出:
['~newnes~', '####imprint####', '++elsevier++', '-corporate-', ':drive:', ';suite;',
'=burlington=', ')usa)', '####imprint####', '(linacre(', '/jordan/', '&hill&',
'%oxford%', '***uk***', '***uk***', '++elsevier++', '$inc$', '§right§', '!reserved!',
'####imprint####', '#exception#', '####imprint####', '*newness*', '***uk***',
'+...+']
[')usa)', '***uk***', '&hill&', ':drive:', '+...+']