2017-03-20 7 views
2

は私が持っているratio.Iネガと正の単語の割合を決定したいと考えているツイートのセットを持って設定を決定し、以下の単純化された辞書の:は、つぶやきの正/負の単語比率が

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.33などを期待しながら、しかし、私はここでしかうまくいかないものに

任意の考え... ... 0.0を取得しますか?

+1

python 2 division? –

+0

出力をfloatにキャストする代わりに、いずれかのオペランドをfloatにキャストします。 – Anbarasan

答えて

1

それは整数の除算を行いますので、私はあなたがPythonの2を、使用していることを前提としています。 あなたはそれを避けるためにフロート()機能を使用する必要があります。

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

を私は現在、あなたがどうかをチェックしている間、あなたが本当にやりたいことは、ツイート内の各単語は、正または負であるかどうかを確認することだと思います全体ツイートは正/負の単語セットになっています。したがって、あなたはそれを見つけることはありませんし、両方の数字が0

に滞在する代わりにつぶやきを分割し、その言葉を反復処理:負の言葉に

for word in tweet.split(): 
    if word in positive_words: 
    count_positive = count_positive + 1 

と同様に。

EDIT:(Schmuddiの答えに貢献)もtweetであなたの文字数を与える代わりにlen(tweet)で割るの正しい比率を、計算するために、あなたは単語数で分割する必要があることに注意してくださいtweet(すなわち、len(tweet.split()))とする。

2

コードにはいくつか問題があります。

Ivayloの答えで指摘したように(1)、あなたは言葉につぶやきを分割する必要があります。これはtweet.split()で行うことができます。

(2)あなたは言葉ではなく、文字でのつぶやきの長さを決定する必要があります16人のキャラクターがthis is terribleであるため、最初のつぶやきためlen(tweet)はあなたに16を与えるが、3つの言葉があります。

(3)のPython 2.xで(ただし、Pythonの3.xので)、i/jような式はあなたcount_positivecount_negative変数の場合と同様に長く関与するすべての変数が整数であるようにするための整数除算でありますあなたのlen(tweet)と同様にこれはフロート区切りであることを確認する必要があります。

ここに、これらの問題を修正するコードのリビジョンがあります。

# You can use the following line to make Python 2.7 behave like Python 3.x 
# with regard to divisions: if you import 'division' from the __future__ 
# module, divisions that use the '/' operator will be float, and divisions 
# that use the '//' will be integer. 
from __future__ import division 

negative_words = ['bad', 'terrible'] 
positive_words = ['outstanding', 'good'] 

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

for tweet in tweets: 
    # split the tweet into words: 
    words = tweet.split() 

    # use list comprehensions to create lists of positive and negative 
    # words in the current tweet, and use 'len()' to get the counts in 
    # each list: 
    count_positive = len([w for w in words if w in positive_words]) 
    count_negative = len([w for w in words if w in negative_words]) 

    # divide the counts by the number of words: 
    ratio_positive = count_positive/len(words) 
    ratio_negative = count_negative/len(words) 

    print(ratio_positive) 
    print(ratio_negative) 

編集:注以前のバージョンがcollectionsモジュールからCounterクラスを使用していること。これは、一般的に非常に有用なクラスですが、現在のケースでは過剰です(まだ動作していません)。

関連する問題