【问题标题】:Better way to identify words that are unique to each document in a corpus识别语料库中每个文档唯一的单词的更好方法
【发布时间】:2020-03-15 17:42:39
【问题描述】:

我创建了一个小型测试语料库:

words = ["he she why fun", "you are why it", "believe it or stop", 'hello goodbye it', 'i goodbye']
print(len(words))

我正在尝试创建一个字典,其中键是唯一的单词,值是它们来自的文档。所以我创建了这个例程:

count = 0
while count < len(words):
    for word in words[count].split():
        p = " ".join(words[0:count]) + " " + " ".join(words[count+1:len(words)])
        if word not in p.split():
            dc[word] = count
    count += 1

print(dc)



{'he': 0, 'she': 0, 'fun': 0, 'you': 1, 'are': 1, 'believe': 2, 'or': 2, 'stop': 2, 'hello': 3, 'i': 4}

这行得通,但它很笨重。有没有办法使用计数矢量化器、TF-IDF 或一些 Spacy 函数,也许可以做到这一点?我还担心可读性,即字典格式看起来不太好。

【问题讨论】:

    标签: python-3.x nlp countvectorizer tfidfvectorizer


    【解决方案1】:

    您可以通过将事物收集到集合中并丢弃已经在集合中的事物来简化此操作。

    dc = dict()
    seen = set()
    for index, sentence in enumerate(words):
        for word in sentence.split():
            if word in seen:
                if word in dc:
                    del dc[word]
            else:
                seen.add(word)
                dc[word] = index
    
    print(dc)
    

    我想您可以尝试将集合与 dict 混为一谈,但我认为拥有两个单独的变量更清洁,并且对于非平凡的数据量可能更有效。

    还要注意使用enumerate 来跟踪您在项目循环中的位置。

    【讨论】:

    • 这确实有效并且避免了使用“while”循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2020-06-18
    • 1970-01-01
    • 2016-09-24
    • 2014-05-18
    相关资源
    最近更新 更多