我有一个15 of的文字。我需要计算出固定窗口大小的单词的共现计数,然后再对它们进行处理。例如,这是我的文字;
“福说呼,酒吧说什么?”
对于窗口大小为4的文本,若要构造共现频率的双图,输出应如下;
字1-字2-计数
福,说,1
foo,呼,1
foo,bar,1
说,呼,2
说,酒吧,2
说,说,1
哇,酒吧,1
呼,什么,1
酒吧,什么,1
说,什么,1
我已经知道有一些工具可以这样做,比如NLTK,但是它不是多线程的,所以对于大小为15 it的文本不起作用。在给定的窗口大小和速度上,有什么工具可以给我单词的共生矩阵吗?
发布于 2017-05-11 11:10:55
我自己也找过这样的工具,但从未找到过。我通常只是写一个脚本来完成它。下面是一个可能对您有用的有一些限制的示例:
import concurrent.futures
from collections import Counter
tokens = []
for _ in range(10):
tokens.extend(['lazy', 'old', 'fart', 'lying', 'on', 'the', 'bed'])
def cooccurrances(idx, tokens, window_size):
# beware this will backfire if you feed it large files (token lists)
window = tokens[idx:idx+window_size]
first_token = window.pop(0)
for second_token in window:
yield first_token, second_token
def harvest_cooccurrances(tokens, window_size=3, n_workers=5):
l = len(tokens)
harvest = []
with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as executor:
future_cooccurrances = {
executor.submit(cooccurrances, idx, tokens, window_size): idx
for idx
in range(l)
}
for future in concurrent.futures.as_completed(future_cooccurrances):
try:
harvest.extend(future.result())
except Exception as exc:
# you may want to add some logging here
continue
return harvest
def count(harvest):
return [
(first_word, second_word, count)
for (first_word, second_word), count
in Counter(harvest).items()
]
harvest = harvest_cooccurrances(tokens, 3, 5)
counts = count(harvest)
print(counts)如果您只运行以下代码,您就应该看到这一点:
[('lazy', 'old', 10),
('lazy', 'fart', 10),
('fart', 'lying', 10),
('fart', 'on', 10),
('lying', 'on', 10),
('lying', 'the', 10),
('on', 'the', 10),
('on', 'bed', 10),
('old', 'fart', 10),
('old', 'lying', 10),
('the', 'bed', 10),
('the', 'lazy', 9),
('bed', 'lazy', 9),
('bed', 'old', 9)]限制
window列表的切分在这里起作用,但是如果您打算对窗口列表片做任何事情,您应该知道这一点。Counter对象,以防阻塞(同样是大列表限制)。野生猜
您可能可以使用spaCy Matcher (请参阅这里)编写类似的东西,但是,我不确定这是否会奏效,因为您需要的通配符仍然有点不稳定(根据我的经验)。
https://stackoverflow.com/questions/43910107
复制相似问题