1
まずは、壊れた英語を申し訳なく思っています。単語の誤りがゼロのときにエラーが発生する
私はこのコードを使用して、「LeBron」または「Curry」という単語がツイートに表示される回数をカウントしています。問題は、つぶやきのいずれも "LeBron"または "Curry"という単語を含まない場合、プログラムがクラッシュすることです。言葉はそこにあり、プログラムは完璧に走っています。各
tweets_data_path = '/Users/HCruz/NetBeansProjects/elections3/data/fetched_tweets.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
def word_in_text(word, text):
word = word.lower()
text = text.lower()
match = re.search(word, text)
if match:
return True
return False
tweets['LeBron'] = tweets['text'].apply(lambda tweet: word_in_text('LeBron', tweet))
tweets['Curry'] = tweets['text'].apply(lambda tweet: word_in_text('Curry', tweet))
LeBron = tweets['LeBron'].value_counts()[True]
Curry = tweets['Curry'].value_counts()[True]
print("LeBron %s" % LeBron)
print("Curry %s" % Curry)
ときtheresの少なくとも1つは、 "カレー" や "レブロンは、" 私はこれを取得:完璧ザッツ
Processing...
LeBron 1
Curry 34
。
しかし、 "LeBron"を削除しても、LeBronの発生がないので、プログラムがクラッシュします。 try/catchとライン44上のコードを囲むことにより、
Hectors-iMac:src HCruz$ python process_tweets.py
Processing...
Traceback (most recent call last):
File "process_tweets.py", line 80, in <module>
s.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sched.py", line 117, in run
action(*argument)
File "process_tweets.py", line 54, in processing
process_tweets()
File "process_tweets.py", line 44, in process_tweets
LeBron = tweets['LeBron'].value_counts()[True]
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/series.py", line 491, in __getitem__
result = self.index.get_value(self, key)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/index.py", line 1038, in get_value
return tslib.get_value_box(s, key)
File "tslib.pyx", line 454, in pandas.tslib.get_value_box (pandas/tslib.c:9561)
File "tslib.pyx", line 469, in pandas.tslib.get_value_box (pandas/tslib.c:9408)
IndexError: index out of bounds
はエラーを得ていないが、私はレブロンを変更=レブロン= 0のためのどれも、それは完全に働きました。ありがとう! –
素晴らしい、あなたがそれを理解してうれしい、乾杯! – davedwards
私の答えがあなたを助けてくれたなら、それを受け入れることを検討してください、ありがとう! – davedwards