-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocess.py
194 lines (153 loc) · 5.85 KB
/
preprocess.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""Preprocessing module."""
# pylint: disable=C0330
# pylint: disable=R0902
#import tensorflow
import argparse
import csv
import json
import logging
import re
import string
import sys
from typing import List
import preprocessor # type: ignore
import nltk # type: ignore
from nltk.stem.wordnet import WordNetLemmatizer # type: ignore
from nltk.tag import pos_tag # type: ignore
from nltk.tokenize import word_tokenize # type: ignore
MAX_TWEETS = -1
DIVISION = 25
def preprocess_tweets(infile: str, outfile: str) -> None:
"""Remove redundant and non-objective posts."""
logger = logging.getLogger("preprocessor")
# Number of Tweets read
counter: int = 0
# List of all Tweets
tweets: List[Tweet] = []
# Begin reading
with open(infile, "r") as csv_file:
# CSV reader
csv_reader = csv.reader(csv_file, delimiter=",")
logger.info("Attached CSV reader")
# Number of Tweets deleted due to URL
url_blocked = 0
# Iterate
for tweet in csv_reader:
# Messaging checkpoints
if not counter % DIVISION:
logger.info("Processed %s Tweets", counter)
# Break at limit
if counter == MAX_TWEETS:
break
# Only add Tweet if it doesn't contain a URL.
# As per Ejieh's master's thesis, the vast majority
# of posts with URLs lack any subjectivity.
ptn = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+#]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
if not bool(re.search(ptn, tweet[0])):
tweets.append(Tweet(tweet))
else:
url_blocked += 1
counter += 1
logger.info("Read %s Tweets in total", counter)
# Finishing message
logger.info("Only %s Tweets were kept", len(tweets))
with open(outfile, "w", encoding="utf-8") as output_file:
tweet_writer = csv.writer(output_file)
i = 1
for tweet in tweets: # type: ignore
tweet_writer.writerow(
[
tweet.full_text, # type: ignore
tweet.created_at, # type: ignore
tweet.source, # type: ignore
tweet.tweet_id, # type: ignore
tweet.retweet_count, # type: ignore
tweet.favorite_count, # type: ignore
tweet.user_name, # type: ignore
tweet.user_id_str, # type: ignore
tweet.user_handle, # type: ignore
tweet.user_location, # type: ignore
tweet.user_desc, # type: ignore
tweet.user_protected, # type: ignore
tweet.user_followers, # type: ignore
tweet.user_created, # type: ignore
tweet.user_verified, # type: ignore
tweet.user_tweet_count, # type: ignore
tweet.cleaned_text, # type: ignore
json.dumps(tweet.cleaned_tokens), # type: ignore
]
)
if not i % DIVISION:
logger.info("Wrote Tweet #%s", i)
i += 1
logger.info("Wrote %s Tweets in total", len(tweets))
class Tweet:
"""Tweet object."""
def __init__(self, tweet_row: List[str]) -> None:
"""Initialize Tweet object."""
# Existing members
self.full_text = tweet_row[0]
self.created_at = tweet_row[1]
self.source = tweet_row[2]
self.tweet_id = tweet_row[3]
self.retweet_count = tweet_row[4]
self.favorite_count = tweet_row[5]
self.user_name = tweet_row[6]
self.user_id_str = tweet_row[7]
self.user_handle = tweet_row[8]
self.user_location = tweet_row[9]
self.user_desc = tweet_row[10]
self.user_protected = tweet_row[11]
self.user_followers = tweet_row[12]
self.user_created = tweet_row[13]
self.user_verified = tweet_row[14]
self.user_tweet_count = tweet_row[15]
# New members
self.cleaned_text = Tweet.clean_tweet(self.full_text)
self.cleaned_tokens = Tweet.normalize(word_tokenize(self.cleaned_text))
@staticmethod
def clean_tweet(full_text: str) -> str:
"""Remove meaningless data, in-place, from Tweets."""
# Said Ozcan's preprocessor
cleaned = str(preprocessor.clean(full_text))
# Remove any remnant mentions
cleaned = str(re.sub(r"@[A-Za-z0-9_]+", "", cleaned))
# Remove non-alpha
cleaned = str(re.sub(r"[^A-Za-z ]+", "", cleaned))
return cleaned
@staticmethod
def normalize(tweet_tokens: List[str]) -> List[str]:
"""Lemmatize a Twitter post.."""
cleaned_tokens = []
# Part of Speech tagging
for token, tag in pos_tag(tweet_tokens):
if tag.startswith("NN"):
pos = "n"
elif tag.startswith("VB"):
pos = "v"
else:
pos = "a"
# Lemmatize
lemmatizer = WordNetLemmatizer()
token = lemmatizer.lemmatize(token, pos)
if len(token) > 0 and token not in string.punctuation:
cleaned_tokens.append(token.lower())
return cleaned_tokens
def main() -> int:
"""Execute standalone."""
arg_p = argparse.ArgumentParser()
arg_p.add_argument("infile", help="input .CSV file")
arg_p.add_argument("outfile", help="output .CSV file")
args = arg_p.parse_args()
logging.basicConfig(
level=logging.INFO, format="[%(levelname)s | %(name)s] %(message)s",
)
nltk.download("punkt")
nltk.download("averaged_perceptron_tagger")
nltk.download("wordnet")
nltk.download("twitter_samples")
nltk.download("stopwords")
preprocess_tweets(args.infile, args.outfile)
return 0
if __name__ == "__main__":
sys.exit(main())