【问题标题】:Multi Threading in NLTK WordNetLemmatizer?NLTK WordNetLemmatizer 中的多线程?
【发布时间】:2018-05-30 18:17:18
【问题描述】:

我正在尝试使用多线程来加快进程。我正在使用 wordnetlemmatizer 对单词进行词形还原,这些单词可以被 sentiwordnet 进一步用于计算文本的情绪。我使用 WordNetLemmatizer 的情绪分析功能如下:

import nltk
from nltk.corpus import sentiwordnet as swn

def SentimentA(doc, file_path):
    sentences = nltk.sent_tokenize(doc)
    # print(sentences)
    stokens = [nltk.word_tokenize(sent) for sent in sentences]
    taggedlist = []
    for stoken in stokens:
        taggedlist.append(nltk.pos_tag(stoken))
    wnl = nltk.WordNetLemmatizer()
    score_list = []
    for idx, taggedsent in enumerate(taggedlist):
        score_list.append([])
        for idx2, t in enumerate(taggedsent):
            newtag = ''
            lemmatized = wnl.lemmatize(t[0])
            if t[1].startswith('NN'):
                newtag = 'n'
            elif t[1].startswith('JJ'):
                newtag = 'a'
            elif t[1].startswith('V'):
                newtag = 'v'
            elif t[1].startswith('R'):
                newtag = 'r'
            else:
                newtag = ''
            if (newtag != ''):
                synsets = list(swn.senti_synsets(lemmatized, newtag))

                score = 0
                if (len(synsets) > 0):
                    for syn in synsets:
                        score += syn.pos_score() - syn.neg_score()
                    score_list[idx].append(score / len(synsets))
    return SentiCal(score_list)

运行 4 个线程后,前 3 个线程出现以下错误,最后一个线程运行良好。

AttributeError: 'WordNetCorpusReader' object has no attribute '_LazyCorpusLoader__args'

我已经尝试按照此 NLTK issue 在本地导入 NLTK 包 并尝试了page 上给出的解决方案。

【问题讨论】:

  • LazyCorpusLoader 应该在 Pool 之前评估 =) 如果没有人回答,我会在今天〜10 小时后回答。

标签: python multithreading python-3.x nltk wordnet


【解决方案1】:

快速破解:

import nltk
from nltk.corpus import sentiwordnet as swn
# Do this first, that'll do something eval() 
# to "materialize" the LazyCorpusLoader
next(swn.all_senti_synsets()) 

# Your other code here. 

更多细节稍后...仍在输入

【讨论】:

  • 当我使用上述提示时,我收到错误:AttributeError: 'SentiWordNetCorpusReader' object has no attribute 'words'。但是,WordNet 确实有一个 Words 属性,我使用的方式与上面显示的相同。我仍然收到相同的错误。奇怪的是,当我在代码中打印 lemmatized 变量时,两个线程都运行了。
  • 抱歉,sentiwordnet 应该是 next(swn.all_senti_synsets()),wordnet 应该是 next(wn.words())
  • 当我增加线程数并在大量文档上运行它时,一些线程仍然因为同样的错误而停止。你能告诉我解决这个问题的方法吗?
  • 请记住,Python 的多线程是一种假的,并且会传递序列化的输出。除非您共享完整的代码和数据集并且其他人尝试复制问题,否则调试问题并不容易。
猜你喜欢
  • 2011-10-03
  • 2019-07-14
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多