neg=['no','not',"don't",'have no interest in']
verb=['like','love','want']
senten=['I love apples.', 'I do not like grapes', 'I have no interest in wanting bananas.','No love for cars']
我想知道我的观点是正面还是负面。如果senden中的字符串仅包含动词,则打印“ 1”。但是如果neg在动词之前出现,我会给它加上“ -1”。
示例:
like +1
love +1
want +1
no like -1
not want -1
don't love -1
代码:
for j in senten:
j=j.lower()
if any(x in j for x in verb):
first_match = list(filter(lambda x: x in j, verb))[0]
loca=j.find(first_match) #location of the first word
#the sentence might be too short.
if int(loca)<=3:
if j[int(loca)-3:int(loca)-1]== "no":
print(j)
print(-1)
continue
elif int(loca)<=4:
if j[int(loca)-3:int(loca)-1]== "no" or j[int(loca)-4:int(loca)-1]== "not":
print(j)
print(-1)
continue
elif int(loca)<=6:
if j[int(loca)-3:int(loca)-1]== "no" or j[int(loca)-4:int(loca)-1]== "not" or j[int(loca)-6:int(loca)-1]== "don't":
print(j)
print(-1)
continue
elif int(loca)<=22:
if j[int(loca)-3:int(loca)-1]== "no" or j[int(loca)-4:int(loca)-1]== "not" or j[int(loca)-6:int(loca)-1]== "don't" or j[int(loca)-20:int(loca)-1]== "have no interest in":
print(j)
print(-1)
continue
print(j)
print(1)
我的代码没有错误,它会打印:
i love apples.
1
i do not like grapes
-1
i have no interest in wanting bananas.
-1
no love for cars
-1
但是我想请教一个更好的写法吗?因为我将在负数中添加更多的单词,我需要做大量的if或statement,这可能没有效率。谢谢:)
答案 0 :(得分:0)
如果我理解正确,那么您正在寻找任何否定词,空格,动词。
for s in senten:
for v in verb:
for n in neg:
if n + ' ' + v in s:
print('found a negative')
答案 1 :(得分:0)
您可以简化以下步骤:
neg=['no','not',"don't",'have no interest in']
verb=['like','love','want']
senten=['I love apples.', 'I do not like grapes', 'I have no interest in wanting bananas.','No love for cars', "There's no sun, but I still love the weather."]
for chk in senten:
cnt=0
for n in neg:
for v in verb:
if n+' '+ v in chk.lower():
cnt+=1
if cnt > 0:
print("(-)", chk)
else:
print("(+)", chk)
结果将如下所示: