【问题标题】:How to return list of unique words from file and sort them alphabetically如何从文件中返回唯一单词列表并按字母顺序排序
【发布时间】:2019-12-19 21:12:43
【问题描述】:

我一直在尝试从文件中返回唯一单词列表,并使用 NLTK 按字母顺序对它们进行排序,但尽管我使用了几种不同的方法,但它不起作用。这是我的代码:

import nltk
from nltk import FreqDist

def get_vocabulary(self):
    with open(self.path, "r") as file:
        split = [line.split('\n') for line in file]
    fdist1 = FreqDist(split)
    unique_words = fdist1.hapaxes()
    return sorted(set(unique_words))

还有错误:

TypeError: unhashable type: 'list'

我尝试过的其他类似方法也引发了类似的错误。该解决方案不必包含 nltk,但如果您能告诉我我在自己的解决方案中犯了哪些错误,我将不胜感激。

【问题讨论】:

    标签: list nltk word-frequency


    【解决方案1】:

    TL;DR

    from collections import Counter
    from nltk import word_tokenize
    
    with open('filename.txt') as fin:
        word_count = Counter(word_tokenize(fin.read()))
    
    
    # Sorted by most common.
    word_count.most_common()
    
    # Sorted alphabetically
    sorted(word_count.items())
    
    # If you just need the words. 
    sorted(word_count)
    

    【讨论】:

    • 它不工作。我需要像 ['albanologie', 'allgemeine', 'als'] 这样的独特词,但我用你的代码得到的是 [('(', 2), (')', 2), ('Albanologie', 1 )]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多