如果不使用NLTK,你可以這樣做:
from collections import Counter
from itertools import product
documents = '''"foo bar is not a sentence" | tag1
"bar bar black sheep is not a real sheep" | tag2
"what the bar foo is not a foo bar" | tag1'''
documents = [i.split('|')[0].strip('" ') for i in documents.split('\n')]
collocations = Counter()
for i in documents:
# Get all the possible word collocations with product
# NOTE: this includes a token with itself. so we need
# to remove the count for the token with itself.
x = Counter(list(product(i.split(),i.split()))) \
- Counter([(i,i) for i in i.split()])
collocations+=x
for i in collocations:
print i, collocations[i]
你會碰上怎麼算的同一詞搭配的句子,比如一個問題,
酒吧酒吧黑羊是不是真羊
('bar','bar')的搭配數是多少?它是1的2嗎?上面的代碼給出了2,因爲第一個酒吧與第二個酒吧搭配,第二個酒吧搭配第一個酒吧。