-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscraper.py
More file actions
77 lines (56 loc) · 2.06 KB
/
scraper.py
File metadata and controls
77 lines (56 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from pprint import pprint
import json
import re
import os
import tweepy
from dotenv import load_dotenv
load_dotenv()
auth = tweepy.OAuthHandler(os.getenv('API_KEY'), os.getenv('SECRET_KEY'))
auth.set_access_token(os.getenv('ACCESS_TOKEN'), os.getenv('ACCESS_SECRET'))
api = tweepy.API(auth)
def fetch_tweet_from_inecnigeria():
return api.user_timeline('inecnigeria', count=1000, tweet_mode='extended')
def analysis_election_result_tweet():
tweets = fetch_tweet_from_inecnigeria()
result_tweets = {}
for tweet in tweets:
tweet_text = tweet.full_text
if is_result_tweet(tweet_text):
state = get_state(tweet_text)
# Bug in getting state when it FCT (patched...)
result_tweets[ state if state else 'FCT'] = tweet_text
return result_tweets
def is_result_tweet(text):
regex = re.compile('Total No: Reg Voters:')
result = regex.search(text)
if result:
return True
return False
def collate_result(text):
result_text = text.split('\n')
party_result_texts = result_text[-6:]
result_by_party = {}
for party_result_text in party_result_texts:
party, number_of_votes = party_result_text.split(':')
result_by_party[party] = number_of_votes.strip()
return dict(sorted(result_by_party.items(), key=lambda kv: int(''.join(kv[1].split(','))), reverse=True))
def get_state(text):
regex = re.compile('State', re.IGNORECASE)
result = regex.search(text)
if result:
return text[: result.start()].split(':')[-1].strip()
def result_scrapper():
result_by_states_text = analysis_election_result_tweet()
with open('result.json', 'w+') as file:
try:
results = json.load(file)
except:
results = {}
for state, text in result_by_states_text.items():
if state not in results:
results[state] = collate_result(text)
json.dump(results, file, indent=4)
def get_results_data():
with open('result.json', 'r') as file:
results = json.load(file)
return results