![](/img/trans.png)
[英]Find the most common number in two lists from a third list, get list with most common elements
[英]List the most common lists, from a list
我有這個代碼
text = open("tags.txt", "r")
mylist = []
metalist = []
for line in text:
mylist.append(line)
if len(mylist) == 5:
metalist.append(mylist)
mylist.pop(0)
這將打開一個文本文件,每行帶有一個POS標簽。 然后,它將前5個POS標簽列表添加到mylist,然后將其添加到金屬專家。 然后,它向下移動到下一行並創建5個POS標簽的下一個序列。 文本文件總共有大約110k〜個標簽。 我需要從金屬專家那里找到最常見的POS標簽序列。 我嘗試使用計數器集合,但列表不可哈希。 解決此問題的最佳方法是什么?
正如其中一條注釋中提到的那樣,您可以簡單地使用標簽的元組,而不使用將與collections
模塊中的Counter
類一起使用的標簽列表。 這是使用問題中代碼的基於列表的方法以及一些優化的方法,因為您必須處理大量POS標簽:
from collections import Counter
GROUP_SIZE = 5
counter = Counter()
mylist = []
with open("tags.txt", "r") as tagfile:
tags = (line.strip() for line in tagfile)
try:
while len(mylist) < GROUP_SIZE-1:
mylist.append(tags.next())
except StopIteration:
pass
for tag in tags: # main loop
mylist.pop(0)
mylist.append(tag)
counter.update((tuple(mylist),))
if len(counter) < 1:
print 'too few tags in file'
else:
for tags, count in counter.most_common(10): # top 10
print '{}, count = {:,d}'.format(list(tags), count)
但是,最好也使用collections
模塊中的deque
而不是list
來執行您的操作,因為前者具有非常高效的O(1),從任一端追加和彈出,而O(n)與后者。 它們還使用較少的內存。
除此之外,自Python v 2.6起,它們還支持maxlen參數,從而消除了在達到所需大小后在末端顯式pop()
元素的需求-因此,基於它們的一個更有效的版本:
from collections import Counter, deque
GROUP_SIZE = 5
counter = Counter()
mydeque = deque(maxlen=GROUP_SIZE)
with open("tags.txt", "r") as tagfile:
tags = (line.strip() for line in tagfile)
try:
while len(mydeque) < GROUP_SIZE-1:
mydeque.append(tags.next())
except StopIteration:
pass
for tag in tags: # main loop
mydeque.append(tag)
counter.update((tuple(mydeque),))
if len(counter) < 1:
print 'too few tags in file'
else:
for tags, count in counter.most_common(10): # top 10
print '{}, count = {:,d}'.format(list(tags), count)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.