wira.indra commited on
Commit
d49f00b
·
1 Parent(s): faf61e8

add twitter feature

Browse files
Files changed (1) hide show
  1. twitter_scraper.py +47 -0
twitter_scraper.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import snscrape.modules.twitter as sntwitter
2
+ import datetime as dt
3
+ import pandas as pd
4
+ import sys
5
+ import os
6
+ import re
7
+ import tqdm
8
+
9
+
10
+ def scrape_tweets(query, max_tweets=10, output_path="./scraper/output/" ):
11
+ tweets_list = []
12
+
13
+ for i,tweet in tqdm(enumerate(sntwitter.TwitterSearchScraper(query).get_items())):
14
+ if max_tweets != -1 and i >= int(max_tweets):
15
+ break
16
+ tweets_list.append([tweet.date, tweet.id, tweet.content, tweet.user.username, tweet.likeCount, tweet.retweetCount, tweet.replyCount, tweet.quoteCount, tweet.url, tweet.lang])
17
+
18
+ df = pd.DataFrame(tweets_list, columns=['Datetime', 'Tweet Id', 'Text', 'Username', 'Likes', 'Retweets', 'Replies', 'Quotes', 'URL', 'Language'])
19
+ df = df[df["Language"] == "in"]
20
+ return df
21
+
22
+ def remove_unnecessary_char(text):
23
+ text = re.sub("\[USERNAME\]", " ", text)
24
+ text = re.sub("\[URL\]", " ", text)
25
+ text = re.sub("\[SENSITIVE-NO\]", " ", text)
26
+ text = re.sub(' +', ' ', text)
27
+ return text
28
+
29
+ def preprocess_tweet(text):
30
+ text = re.sub('\n',' ',text)
31
+ text = re.sub('^(\@\w+ ?)+',' ',text)
32
+ text = re.sub(r'\@\w+',' ',text)
33
+ text = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(http?://[^\s]+))',' ',text)
34
+ text = re.sub('/', ' ', text)
35
+ text = re.sub(' +', ' ', text)
36
+ return text
37
+
38
+ def remove_nonaplhanumeric(text):
39
+ text = re.sub('[^0-9a-zA-Z]+', ' ', text)
40
+ return text
41
+
42
+ def preprocess_text(text):
43
+ text = preprocess_tweet(text)
44
+ text = remove_unnecessary_char(text)
45
+ text = remove_nonaplhanumeric(text)
46
+ text = text.lower()
47
+ return text