forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTweet Pre-Processing.py
134 lines (66 loc) · 1.71 KB
/
Tweet Pre-Processing.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
#!/usr/bin/env python
# coding: utf-8
# In[10]:
import numpy as np
from nltk.corpus import twitter_samples
import matplotlib.pyplot as plt
import random
# In[ ]:
# analysing tweets from the corpus
# In[14]:
positive_tweets = twitter_samples.strings("positive_tweets.json")
# In[15]:
negative_tweets = twitter_samples.strings("negative_tweets.json")
# In[16]:
all_tweets = positive_tweets + negative_tweets
# In[17]:
# Analysing sampels tweets
print(positive_tweets[random.randint(0, 5000)])
# In[19]:
""" There are 4 basic steps in pre-processing of any text
1.Tokenizing
2.Removing hyper links if any
3.Converting to lower case
4.Removing punctuations
5.steeming of the word"""
import re
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
# In[20]:
# Removing Hyper links
tweet = all_tweets[1]
# removing RT words in the tweet
tweet = re.sub(r"^RT[\s]+", "", tweet)
# removing hyperlinks in the tweet
tweet = re.sub(r"https?:\/\/.*[\r\n]*", "", tweet)
# removing #symbol from the tweet
tweet = re.sub(r"#", "", tweet)
print(tweet)
# In[22]:
# Tokenizing
tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)
tokens = tokenizer.tokenize(tweet)
print(tokens)
# In[23]:
# Remving stop words and punctuation marks
stoper = stopwords.words("english")
punct = string.punctuation
print(stoper)
print(punct)
# In[24]:
cleaned = []
for i in tokens:
if i not in stoper and i not in punct:
cleaned.append(i)
print(cleaned)
# In[25]:
# stemming
stemmer = PorterStemmer()
processed = []
for i in cleaned:
st = stemmer.stem(i)
processed.append(st)
print(processed)
# In[ ]: