在Python列表中查找特定索引的值
我有一个简单的python程序在Python列表中查找特定索引的值,python,list,nltk,Python,List,Nltk,我有一个简单的python程序 from nltk.tokenize import word_tokenize negation ='no','not','never'.split(',') list2 = 'miss,loss,gone,give up,lost'.split(',') sentence = 'loss money' if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
from nltk.tokenize import word_tokenize
negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'
if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
print 'sad'
else:
print 'not sad'
这会导致错误,这是
TypeError: 'bool' object has no attribute '__getitem__'
我需要的是,我想检查句子中是否有单词在列表2中。如果是,则要检查其before索引值是否在否定列表中。如果是,应该是“不悲伤”
例如,“我想他”应该悲伤,“我不想他”应该不悲伤
谁能帮帮我 你的
if
的第二部分写得不好。
首先查看any(列表2中的单词表示单词中的单词(句子))
,它返回一个布尔值。然后尝试提取此布尔值的最后一个元素([-1]
),该元素返回错误
无需在此处使用nltk
库,只需使用.split()
:
编辑新版本以考虑@Baldrickk的好评。
我又考虑了两个案子。如果没有单词属于list2
,则会打印“happy”。如果有几个单词属于列表2
,它会检查前面的每个单词,而不仅仅是第一个单词
negation = {'no', 'not', 'never'}
list2 = {'miss', 'loss', 'gone', 'give up', 'lost'}
def f(sentence):
s = sentence.split()
l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
if len(l) > 0:
for e in l:
# Check previous word
if s[e-1] not in negation:
print 'sad'
else:
print 'not sad'
else:
print 'happy'
l = ['loss money', 'I miss him', 'I not miss him', 'happy new year', 'I am not here I am gone']
for e in l:
f(e)
# sad / sad / not sad / happy / sad
首先,这里有很多问题:
- 如果你要浏览一组单词,请使用集合,而不是列表。e、 g.
negations={'no','not','never'}
永远不会在句子中作为标记出现李>“放弃”
any()
listobj[-1::][/code>返回仅包含最后一个元素的列表切片
- 您没有尝试从列表或容器中提取项目,因为
返回布尔值,您正在尝试将布尔值视为容器。这就是导致您可以看到的错误的原因any()
如果要根据其他人的位置访问列表中的项目,我建议从索引for循环开始:
for index, value in enumerate(var):
last_word=var[index-1] if index > 0 else None
而且像单词标记化这样的操作只做一次,不需要反复做
示例解决方案:
def sad_sentence(sentence):
wordlist=sentence.split()
negations={'no','not','never'}
negphrases={'miss','loss','gone','give up','lost'}
for index, word in enumerate(wordlist):
last_word=wordlist[index-1] if index > 0 else None
if word in negphrases:
if last_word in negations:
print 'not sad'
else:
print 'sad'
break;
print 'not sad'
这导致:
>>> sad_sentence("I am not gone")
not sad
>>> sad_sentence("I am not here I am gone")
sad
>>>
注意,当找到与list2匹配的词时,您并不是在寻找前面的词,而是在寻找一个否定词。“我不在这里,我走了”将返回
“不悲伤”
,当所描述的算法返回“悲伤”
@Baldrickk谢谢你的评论,我没有注意到!我更新以修复此问题:)很好,这正是我所期望的。谢谢。@Nuageux我能在Lambda表达式中使用这个函数吗?新版本很好,我很喜欢查找索引,这很聪明。当然,它会在输入时中断,比如:“想他吗?很高兴我不是“
”(当我喜欢我的解决方案时,这又回来了“不悲伤”
,它应该是“悲伤”
)我将把它为什么会破裂留给你。非常好的解释。在检查你的答案时,我改正了很多错误
>>> sad_sentence("I am not gone")
not sad
>>> sad_sentence("I am not here I am gone")
sad
>>>