-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCleaning.py
More file actions
68 lines (53 loc) · 1.62 KB
/
Copy pathCleaning.py
File metadata and controls
68 lines (53 loc) · 1.62 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
# Importing basic Libraries for EDA
import pandas as pd
import regex as re
from ast import literal_eval
import warnings
warnings.filterwarnings("ignore")
pd.set_option("display.max_columns", 10)
# Create a list of stopwords
import nltk
import spacy
stopwords_nltk = nltk.corpus.stopwords.words("english")
nlp = spacy.load("en_core_web_lg")
stopwords_spacy = nlp.Defaults.stop_words
stopwords = list(
set(
stopwords_nltk
+ list(stopwords_spacy)
+ list(stopwords_nltk)
+ list("abdefghijklmnopqstuvwxyz")
)
)
print(len(stopwords))
df = pd.read_csv("Data/combined_df.csv")
df.head()
# Dropping the rows with missing values in the body and tags columns and dropping the duplicates.
df.dropna(inplace=True)
df.drop_duplicates(inplace=True)
df["Text"] = df["Head"] + " " + df["Body"]
# Cleaning the tags
df["Tags Count"] = df["Tags"].apply(lambda x: len(literal_eval(x)))
df["Tags Count"] = df["Tags Count"].astype("int16")
df.info()
# Removing the rows with more than 5 tags
df = df[df["Tags Count"] <= 5]
def clean_text(text):
text = re.sub(r"<.*?>", "", text)
text = re.sub(r"[^a-zA-Z]", " ", text)
text = re.sub(r"\s+", " ", text)
text = text.lower()
text = text.strip()
# Lemmatization and removing stopwords
text = " ".join(
[
token.lemma_
for token in nlp(text)
if token.lemma_ not in stopwords and token.lemma_ != "-PRON-"
]
)
return text
df["Text"] = df["Text"].apply(clean_text)
df.head()
df.to_csv("Data/cleaned_data.csv", index=False)
## Now our data is in a good shape, we can start to do some analysis on it.