【问题标题】:AttributeError: 'function' object has no attribute 'lower'AttributeError: 'function' 对象没有属性 'lower'
【发布时间】:2016-01-22 10:25:00
【问题描述】:

我正在尝试使用 sentiwordnet 文本文件“SentiWordNet_3.0.0_20130122.txt”。当我导入 sentiwordnet.py 文件并尝试运行它时,我收到如下错误:

错误发生为:

--------------------------------------------------------------------------         AttributeError
Traceback (most recent call last)
<ipython-input-13-6e4eb476b4b2> in <module>()
----> 1 happy = cv.senti_synsets('happy', 'a')

C:\Users\Desktop\fp\sentiwordnet.pyc in     senti_synsets(self, string, pos)
     65         synset_list = wn.synsets(string, pos)
     66         for synset in synset_list:
---> 67             sentis.append(self.senti_synset(synset.name))
     68         sentis = filter(lambda x : x, sentis)
     69         return sentis

C:\Users\Desktop\fp\sentiwordnet.pyc in senti_synset(self, *vals)
     52             return SentiSynset(pos_score, neg_score, synset)
     53         else:
---> 54             synset = wn.synset(vals[0])
     55             pos = synset.pos
     56             offset = synset.offset

C:\Users\Anaconda2\lib\site-packages\nltk\corpus\reader\wordnet.pyc in synset(self, name)
     1227     def synset(self, name):
     1228         # split name into lemma, part of speech and synset number
---> 1229         lemma, pos, synset_index_str = name.lower().rsplit('.', 2)
     1230         synset_index = int(synset_index_str) - 1
     1231 

AttributeError: 'function' object has no attribute 'lower'

我的代码:

import sentiwordnet as snw
SWN_FILENAME = "SentiWordNet_3.0.0_20130122.txt"
cv = snw.SentiWordNetCorpusReader(SWN_FILENAME)
happy = cv.senti_synsets('happy', 'a')
print happy

【问题讨论】:

  • 根据报错信息,wordnet.pyc第1229行的“name”本应是字符串,却是函数。
  • 是的,可能没有将字符串传递给 senti_synsets 方法,禁止它的代码有什么问题?CorpusReader 无法读取文件吗?
  • 也许可以试试synset.name()

标签: python sentiment-analysis text-analysis senti-wordnet


【解决方案1】:

你能试试下面的代码吗:

import nltk.corpus.reader.sentiwordnet as snw
SWN_FILENAME = "SentiWordNet_3.0.0_20130122.txt"
cv = snw.SentiWordNetCorpusReader('', [SWN_FILENAME])
happy = cv.senti_synsets('happy', 'a')
print(happy)

我认为您使用的 sentiwordnet.py 文件与您安装的 nltk 包不匹配。如果我使用这种不匹配的对,我能够重现您的错误。上面的代码使用了 nltk 包附带的 SentiWordNetCorpusReader(见NLTK sources);然而,读者的构造函数想要一个'root'作为第一个参数(我不知道nltk并且不知道这可能是什么;-)),第二个它想要一个文件ID列表(我认为他们的意思文件名,但代码似乎足够灵活,可以接受文件名作为字符串)。

我猜你也可以使用与你的 sentiwordnet.py 文件匹配的另一个 nltk 包版本。

【讨论】:

  • 是的!知道了。我认为从 nltk 包中导入 sentiwordet 会更好
  • 问题是类的结构看起来发生了变化。通过使用 nltk 软件包版本,您应该是安全的(并使用较新的版本,看起来)。
猜你喜欢
  • 2020-10-06
  • 2016-04-15
  • 2016-01-30
  • 2020-12-08
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
相关资源
最近更新 更多