Python 确定tweet集合中的正/负单词比率

Python 确定tweet集合中的正/负单词比率,python,Python,我有一组tweet,我想在其中确定否定词和肯定词的比例。我有以下简化词典: negative_words = ['bad', 'terrible'] positive_words = ['outstanding', 'good'] 我编写了以下代码来分析它们: tweets = ["this is terrible", "this is very good"] for tweet in tweets: count_positive = 0 count_negative = 0 if(

我有一组tweet,我想在其中确定否定词和肯定词的比例。我有以下简化词典:

negative_words = ['bad', 'terrible']
positive_words = ['outstanding', 'good']
我编写了以下代码来分析它们:

tweets = ["this is terrible", "this is very good"]

for tweet in tweets:
 count_positive = 0
 count_negative = 0

 if(tweet in positive_words):
  count_positive = count_positive + 1
 if(tweet in negative_words):
  count_negative = count_negative + 1

 ratio_positive = count_positive / len(tweet)
 ratio_negative = count_negative / len(tweet)
 ratio_negative = float(ratio_negative)
 ratio_positive = float(ratio_positive)

 print(ratio_positive)
 print(ratio_negative)
这段代码的输出应该是肯定词与否定词的比率。但是我只得到0.0。。。而我期望0.33等等


有什么想法吗?

我假设您使用的是Python 2,因为它将执行整数除法。 您应该使用float()函数来避免它:

>>> 5 / 2
2
>>> float (5) / 2
2.5

我认为你真正想做的是检查tweet中的每个词是肯定的还是否定的,而目前你正在检查整个tweet是否在肯定/否定词集中。因此,你永远找不到它,两个数字都保持在0

相反,拆分推文并迭代其文字:

for word in tweet.split():
  if word in positive_words:
    count_positive = count_positive + 1
对于否定词也是如此


编辑:(参与Schmuddi的回答)还请注意,为了计算正确的比率,您需要除以
len(tweet)
,而不是除以
len(tweet)
,后者将给出
tweet
中的字符数,您需要除以
tweet
中的单词数(即
len(tweet.split())
).

您的代码存在一些问题

(1) 正如Ivaylo在回答中指出的那样,你需要将推文拆分成文字。您可以通过
tweet.split()
实现这一点

(2) 你需要用文字而不是字符来确定tweet的长度:
len(tweet)
第一条tweet给你的是
16
,因为
中有16个字符,这很糟糕,但有3个单词

(3) 在Python2.x中(但不是在Python3.x中),
i/j
这样的表达式是一个整数除法,只要所有涉及的变量都是整数,就可以使用
count\u positive
count\u negative
变量以及
len(tweet)
。您必须确保这是一个浮点除法

下面是您的代码修订版,可以修复这些问题

#您可以使用下面这行代码使Python 2.7的行为类似于Python 3.x
#关于部门:如果您从未来导入“部门”
#模块中,使用“/”运算符的除法将是浮点除法,而除法
#使用“/”的将是整数。
来自未来进口部
否定词=[“坏”、“可怕”]
积极的词语=[“优秀的”,“好的”]
tweets=[“这太糟糕了”,“这太好了”]
对于推文中的推文:
#将推文拆分为文字:
words=tweet.split()
#使用列表理解创建肯定和否定的列表
#并使用“len()”获取当前推文中的计数
#每个列表:
count_positive=len([w表示w表示w,如果w表示w表示正的话])
count_negative=len([w表示w,如果w表示否定词])
#将计数除以字数:
比率=计数/长度(字)
比率为负=计数为负/长(字)
打印(正比例)
打印(比率\负片)

编辑:请注意,早期版本使用了
集合
模块中的类。总的来说,这是一个非常有用的类,但在本例中,它的功能有些过火(而且还没有完全发挥作用)。

python 2除法?与其将输出强制转换为浮点,不如将任何操作数强制转换为浮点。