【问题标题】:concordance for a phrase using NLTK in Python在 Python 中使用 NLTK 的短语的一致性
【发布时间】:2015-11-19 20:07:27
【问题描述】:

是否可以在 NLTK 中获得短语的一致性?

import nltk
from nltk.corpus import PlaintextCorpusReader

corpus_loc = "c://temp//text//"
files = ".*\.txt"
read_corpus = PlaintextCorpusReader(corpus_loc, files)
corpus  = nltk.Text(read_corpus.words())
test = nltk.TextCollection(corpus_loc)

corpus.concordance("claim")

例如上面的返回

on okay okay okay i can give you the claim number and my information and
 decide on the shop okay okay so the claim number is xxxx - xx - xxxx got

现在如果我尝试corpus.concordance("claim number") 它不起作用...我确实有代码可以通过使用.partition() 方法和一些进一步的编码来做到这一点...但我想知道是否使用concordance 也可以做到这一点。

【问题讨论】:

  • NLTK.text.concordance 似乎只需要一个词。但是,一种选择是将两个文本中的“claim number”替换为“claim_number”,并获得“claim_number”的一致性。

标签: python nlp nltk


【解决方案1】:

我将这个解决方案拼凑在一起......

def n_concordance_tokenised(text,phrase,left_margin=5,right_margin=5):
    #concordance replication via https://simplypython.wordpress.com/2014/03/14/saving-output-of-nltk-text-concordance/

    phraseList=phrase.split(' ')

    c = nltk.ConcordanceIndex(text.tokens, key = lambda s: s.lower())

    #Find the offset for each token in the phrase
    offsets=[c.offsets(x) for x in phraseList]
    offsets_norm=[]
    #For each token in the phraselist, find the offsets and rebase them to the start of the phrase
    for i in range(len(phraseList)):
        offsets_norm.append([x-i for x in offsets[i]])
    #We have found the offset of a phrase if the rebased values intersect
    #--
    # http://stackoverflow.com/a/3852792/454773
    #the intersection method takes an arbitrary amount of arguments
    #result = set(d[0]).intersection(*d[1:])
    #--
    intersects=set(offsets_norm[0]).intersection(*offsets_norm[1:])

    concordance_txt = ([text.tokens[map(lambda x: x-left_margin if (x-left_margin)>0 else 0,[offset])[0]:offset+len(phraseList)+right_margin]
                    for offset in intersects])

    outputs=[''.join([x+' ' for x in con_sub]) for con_sub in concordance_txt]
    return outputs

def n_concordance(txt,phrase,left_margin=5,right_margin=5):
    tokens = nltk.word_tokenize(txt)
    text = nltk.Text(tokens)

    return

n_concordance_tokenised(text,phrase,left_margin=left_margin,right_margin=right_margin)

n_concordance_tokenised(text1,'monstrous size')
>> [u'one was of a most monstrous size . ... This came towards ',
    u'; for Whales of a monstrous size are oftentimes cast up dead ']

【讨论】:

    【解决方案2】:

    如果您阅读@b3000 挖掘的issue 下的讨论,您会发现很奇怪,多词索引实际上是可用的——但只能在图形索引工具中,您可以启动像这样:

    >>> from nltk.app import concordance
    >>> concordance()
    

    【讨论】:

      【解决方案3】:

      根据这个issue,现在还不能使用concordance() 函数搜索多个单词。

      【讨论】:

        猜你喜欢
        • 2017-02-03
        • 1970-01-01
        • 2014-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        相关资源
        最近更新 更多