python - 我可以使用 BigramCollocationFinder (nltk) 来遵守文档边界吗?

标签 python nlp nltk collocation

我正在使用 NLTK 对许多不同的文档进行一些分析。这些文档的内容意味着它们都倾向于以相同的标记结束和开始。

我将文档标记为列表列表,然后使用 BigramCollocationFinder.from_documents 创建查找器。当我按原始频率对 ngram 进行评分时,我注意到最常见的情况是结束字符/开始字符。这表明它将所有文档运行到一个文档中,并在整个文档中查找我不想要的 ngram。

代码示例:

line_tokenizer = nltk.RegexpTokenizer('\{|\}|[^,"}]+')
seqs = ["{B,C}", "{B,A}", "{A,B,C}"]
documents = [line_tokenizer.tokenize(s) for s in seqs]
finder = BigramCollocationFinder.from_documents(documents)
bigram_measures = nltk.collocations.BigramAssocMeasures()
print(finder.score_ngrams(bigram_measures.raw_freq))

这会产生以下输出:

[(('B', 'C'), 0.15384615384615385), 
 (('C', '}'), 0.15384615384615385), 
 (('{', 'B'), 0.15384615384615385), 
 (('}', '{'), 0.15384615384615385), 
 (('A', 'B'), 0.07692307692307693), 
 (('A', '}'), 0.07692307692307693), 
 (('B', 'A'), 0.07692307692307693), 
 (('{', 'A'), 0.07692307692307693)]

ngram }{ 出现在列表中,但它不应该出现在列表中,因为 }{ 永远不会彼此相邻出现。

是否有其他方法可以解决此问题以避免 }{ 出现在列表中?

最佳答案

我相信您想要保留像 {AC} 这样的二元组,因为有时知道某些单词总是出现在句子的末尾或开头是件好事。所以黑客:

bigram_measure 中删除 }{ 二元组,然后使用 1-prob('}{') 重新计算其他二元组的概率.

import nltk
line_tokenizer = nltk.RegexpTokenizer('\{|\}|[^,"}]+')
seqs = ["{B,C}", "{B,A}", "{A,B,C}"]
documents = [line_tokenizer.tokenize(s) for s in seqs]
finder = nltk.collocations.BigramCollocationFinder.from_documents(documents)
bigram_measures = nltk.collocations.BigramAssocMeasures()
# Put bigram measures into a dict for easy access
x = dict(finder.score_ngrams(bigram_measures.raw_freq))

# Re-adjust such that the score of 
# each bigram is divided by 1-prob('}{')
newmax = 1- x[('}','{')]

# Remove "}{" from bigrams.
del x[('}','{')]

# Recalcuate prob for each bigram with newmax
y =[(i,j/float(newmax)) for i,j in x.iteritems()]
print y

[(('B', 'C'), 0.18181818181818182), (('C', '}'), 0.18181818181818182), (('B', 'A'), 0.09090909090909091), (('{', 'A'), 0.09090909090909091), (('{', 'B'), 0.18181818181818182),  (('A', 'B'), 0.09090909090909091), (('A', '}'), 0.09090909090909091)]

关于python - 我可以使用 BigramCollocationFinder (nltk) 来遵守文档边界吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19049270/

相关文章:

python - 暂停和恢复功能

python - sklearn 管道中特定于列的处理

用于版本控制和多语言的数据库结构

java - 如何通过 OpenNLP 从 HTML 格式的电子邮件文件中提取数据?

python - 在 python NLTK 中平滑

python - 属性错误: 'list' object has no attribute 'split' when i try to split a row from csv file

python - BeautifulSoup 解析 'findAll' 运行错误

python - Scipy 优化算法? (用于最小化神经网络成本函数)- python

python - tensorflow 代码TypeError : unsupported operand type(s) for *: 'int' and 'Flag'

python - 如何使用 python 对连续对中的字符串进行标记?