【问题标题】:Get the category of a given sentence from a categorized corpus using NLTK使用 NLTK 从分类语料库中获取给定句子的类别
【发布时间】:2017-01-30 16:51:16
【问题描述】:

使用 NLTK,我创建了一个包含大约 10 万个句子的分类语料库,分为 36 个类别。

我可以像这样访问特定类别的句子:

romantic_comedies_sents = (my_corpus.sents(categories='romantic_comedies'))

但是,给定一个标记化 list 形式的句子,例如 ["You", "had", "me", "at", "hello"],我想有效地识别它出现的类别。有没有快速的方法?

我尝试创建和使用以句子为键、类别为值的字典,但在我的计算机上创建此字典需要很长时间(尤其是与 NLTK 的内置方法相比),我想知道是否有更好的这样做的方式,最好使用 NLTK。

最终我试图为每个句子都采用这种结构:

(["You", "had", "me", "at", "hello"], set("romantic_comedies"))

提前感谢您的帮助。

【问题讨论】:

    标签: python nltk corpus


    【解决方案1】:

    prefix tree 是创建将序列映射到值的字典的有效方法。下面是一个简单的实现:

    class Node(object):
        def __init__(self, word=None):
            self.word = word
            self.children = {}
            self.categories = set()
    
        def add(self, sentence, category):
            if len(sentence):
                word = sentence[0]
                sentence = sentence[1:]
                if word not in self.children:
                    self.children[word] = Node(word);
                self.children[word].add(sentence, category)
            else:
                self.categories.add(category)
    
        def find(self, sentence):
            if len(sentence):
                word = sentence[0]
                sentence = sentence[1:]
                if word not in self.children:
                    return []
                return self.children[word].find(sentence)
            else:
                return self.categories
    
    class PrefixTree(object):
        def __init__(self):
            self.root = Node()
    
        def add(self, sentence, category):
            self.root.add(sentence, category)
    
        def find(self, sentence):
            return self.root.find(sentence)
    

    像这样使用它:

    def main():
        tree = PrefixTree()
        sentence = ["You", "had", "me", "at", "hello"]
        tree.add(sentence, "romantic_comedies")
        print tree.find(sentence)
    

    输出:

    设置(['浪漫喜剧'])

    【讨论】:

    • 非常感谢您的回复。明天我会接受你的回答,除非有人知道在 NLTK 中这样做的方法!
    • 再次感谢您的贡献,但事实证明问题出在其他地方。
    【解决方案2】:

    NLTK 的语料库阅读器的 sents() 函数返回一个列表列表。对于循环创建将句子映射到类别的字典来说,这不是一种特别有效的结构。

    答案是将句子转换为元组,将句子列表转换为集合(我只需要不同的句子)。

    转换后,用于创建将句子映射到类别的字典的循环在 18 秒内完成,而不是整晚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2012-02-07
      • 2017-03-25
      • 1970-01-01
      • 2015-07-22
      • 2018-04-07
      相关资源
      最近更新 更多