-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep1_preprocess_emoji.py
More file actions
97 lines (73 loc) · 2.67 KB
/
Copy pathStep1_preprocess_emoji.py
File metadata and controls
97 lines (73 loc) · 2.67 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#encoding="utf8"
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
import os
import re
#import nltk
#nltk.download()
import simplejson as json
#import pickle
import emoji
from emoji.unicode_codes import UNICODE_EMOJI
#import numpy as np
def rm_html_tags(str):
html_prog = re.compile(r'<[^>]+>',re.S)
return html_prog.sub('', str)
def rm_html_escape_characters(str):
pattern_str = r'"|&|<|>| |"|&|<|>| |似|眼|格|+|值|尼'
escape_characters_prog = re.compile(pattern_str, re.S)
return escape_characters_prog.sub('', str)
def rm_at_user(str):
return re.sub(r'@[a-zA-Z_0-9]*', '', str)
def rm_url(str):
return re.sub(r'http[s]?:[/+]?[a-zA-Z0-9_\.\/]*', '', str)
def rm_repeat_chars(str):
return re.sub(r'(.)(\1){2,}', r'\1\1', str)
def rm_hashtag_symbol(str):
return re.sub(r'#', '', str)
def rm_time(str):
return re.sub(r'[0-9][0-9]:[0-9][0-9]', '', str)
# process emoji to words
def sub_emoji(str1):
final_str = ""
for word in str1.split():
if word in emoji.UNICODE_EMOJI:
emoji_description = UNICODE_EMOJI[word]
emoji_description_list = emoji_description.split("_")
word = ' '.join(emoji_description_list)
print()
final_str += " "
final_str += str(word)
return final_str
def pre_process(str):
# do not change the preprocessing order only if you know what you're doing
str = str.lower()
str = rm_url(str)
str = rm_at_user(str)
str = rm_repeat_chars(str)
str = rm_hashtag_symbol(str)
str = rm_time(str)
str = sub_emoji(str)
return str
if __name__ == "__main__":
data_dir = './data' ##Setting your own file path here.
x_filename = 'tweets.txt'
y_filename = 'labels.txt'
##load and process samples
print('start loading and process samples...')
words_stat = {} # record statistics of the df and tf for each word; Form: {word:[tf, df, tweet index]}
tweets = []
cnt = 0
with open(os.path.join(data_dir, x_filename), encoding='utf-8') as f:
for i, line in enumerate(f):
tweet_obj = json.loads(line.strip(), encoding='utf-8')
content = tweet_obj['text'].replace("\n"," ")
postprocess_tweet = pre_process(content)
tweets.append( postprocess_tweet )
###Re-process samples, filter low frequency words...
fout = open(os.path.join(data_dir, 'tweets_processed_emoji.txt'), 'w', encoding='utf-8')
for tweet in tweets:
fout.write('%s\n' %tweet)
fout.close()
print("Preprocessing is completed")