forloop中的append函数不工作

2024-04-20 11:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个情感分析领域的代码。我有一本字典(.txt),里面的单词都是被评分的,比如“好,2”和“坏,-3”。现在我想让Python把一个给定句子中的正反两方面数一数。我的代码片段如下所示:

text =''

result = []
for sentence in sent_tokenize(text):
    pos = 0
    neg = 0
    for word in word_tokenize(sentence):
        score = Dictionary.get(word, 0)
        if score > 0:
            pos += score
            if score < 0:
                neg += score
                result.append([pos, neg])

for s in result: print(s)

print(result)

所以我希望结果像这样:[5, -6]。 但是我得到一个空结果:[]。 你知道我做错了什么吗?你知道吗


Tags: 代码textinposforifresultsentence
1条回答
网友
1楼 · 发布于 2024-04-20 11:34:13

score不能同时小于和大于零:

if score > 0:
    pos += score
    if score < 0:
        neg += score
        result.append([pos, neg])

将代码更改为:

result = []
for sentence in sent_tokenize(text):
    pos = 0
    neg = 0
    for word in word_tokenize(sentence):
        score = Dictionary.get(word, 0)
        if score > 0:
            pos += score
        if score < 0:
            neg += score
    result.append([pos, neg])

注意result.append([pos, neg])的缩进。这会给你一个新的机会 每个句子有一对pos, neg。你知道吗

相关问题 更多 >