将下载的字符串与Python中的列表进行比较

2024-09-24 02:25:06 发布

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

我正在尝试用Python创建一个情绪分析器,它可以下载文本,并对照一系列负面和正面的单词进行分析。对于文本中与poswords.txt文件应该有一个+1分数,对于中文本中的每个匹配项negwords.txt文件应该有一个-1分数,文本的总分数将是情感分数。这是我一直试图做到的,但我一直只得到0分。你知道吗

下面的答案似乎不起作用,我的情绪得分一直是0。你知道吗

 split = text.split()
    poswords = open('poswords.txt','r')
    for word in split:
        if word in poswords:
            sentimentScore +=1
    poswords.close()

    negwords = open('negwords.txt','r')
    for word in split:
        if word in negwords:
            sentimentScore -=1
    negwords.close()

Tags: 文件in文本txtforcloseifopen
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:06

代码中的poswordsnegwords只是文件句柄,而不是读取这些文件中的单词。你知道吗

此处:

split = text.split()
poswords = open('poswords.txt','r')
pos = []
for line in poswords:
    pos.append(line.strip())
for word in split:
    if word in pos:
        sentimentScore +=1
poswords.close()

negwords = open('negwords.txt','r')
neg = []
for line in negwords:
    neg.append(line.strip())
for word in split:
    if word in neg:
        sentimentScore -=1
negwords.close()

如果文件很大,上述方法就不是最佳解决方案。为肯定词和否定词创建词典:

input_text = text.split() # avoid using split as a variable name, since it is a keyword
poswords = open('poswords.txt','r')
pos_dict = defaultdict(int)
for line in poswords:
    pos_dict[line.strip()] += 1
poswords.close()

negwords = open('negwords.txt','r')
neg_dict = defaultdict(int)
for line in negwords:
    neg_dict[line.strip()] += 1
negwords.close()

sentiment_score = 0
for word in input_text:
    if word in pos_dict:
        sentiment_score += 1
    elif word in neg_dict:
        sentiment_score -=1

相关问题 更多 >