【问题标题】:Lemmatization of a list of words单词列表的词形还原
【发布时间】:2016-03-07 15:29:18
【问题描述】:

所以我有一个文本文件中的单词列表。我想对它们进行词形还原以删除具有相同含义但时态不同的单词。喜欢尝试,尝试等。当我这样做时,我不断收到类似 TypeError: unhashable type: 'list' 的错误

    results=[]
    with open('/Users/xyz/Documents/something5.txt', 'r') as f:
       for line in f:
          results.append(line.strip().split())

    lemma= WordNetLemmatizer()

    lem=[]

    for r in results:
       lem.append(lemma.lemmatize(r))

    with open("lem.txt","w") as t:
      for item in lem:
        print>>t, item

如何对已经是标记的单词进行词形还原?

【问题讨论】:

    标签: python nltk lemmatization


    【解决方案1】:

    WordNetLemmatizer.lemmatize 方法可能需要一个字符串,但您传递给它的是一个字符串列表。这给了你TypeError 异常。

    line.split() 的结果是一个字符串列表,您将其作为列表附加到 results 即列表列表。

    你想使用results.extend(line.strip().split())

    results = []
    with open('/Users/xyz/Documents/something5.txt', 'r') as f:
        for line in f:
            results.extend(line.strip().split())
    
    lemma = WordNetLemmatizer()
    
    lem = map(lemma.lemmatize, results)
    
    with open("lem.txt", "w") as t:
        for item in lem:
            print >> t, item
    

    或在没有中间结果列表的情况下进行重构

    def words(fname):
        with open(fname, 'r') as document:
            for line in document:
                for word in line.strip().split():
                    yield word
    
    lemma = WordNetLemmatizer()
    lem = map(lemma.lemmatize, words('/Users/xyz/Documents/something5.txt'))
    

    【讨论】:

      【解决方案2】:
      Open a text file and and read lists as results as shown below
      fo = open(filename)
      results1 = fo.readlines()
      
      results1
      ['I have a list of words in a text file', ' \n I want to perform lemmatization on them to remove words which have the same meaning but are in different tenses', '']
      
      # Tokenize lists
      
      results2 = [line.split() for line in results1]
      
      # Remove empty lists
      
      results2 = [ x for x in results2 if x != []]
      
      # Lemmatize each word from a list using WordNetLemmatizer
      
      from nltk.stem.wordnet import WordNetLemmatizer
      lemmatizer = WordNetLemmatizer()
      lemma_list_of_words = []
      for i in range(0, len(results2)):
           l1 = results2[i]
           l2 = ' '.join([lemmatizer.lemmatize(word) for word in l1])
           lemma_list_of_words.append(l2)
      lemma_list_of_words
      ['I have a list of word in a text file', 'I want to perform lemmatization on them to remove word which have the same meaning but are in different tense']
      
      Please look at the lemmatized difference between lemma_list_of_words and results1.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        • 2014-11-02
        • 2018-01-05
        • 1970-01-01
        • 2021-10-09
        相关资源
        最近更新 更多