-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreprocessing.py
More file actions
68 lines (60 loc) · 2.22 KB
/
Copy pathpreprocessing.py
File metadata and controls
68 lines (60 loc) · 2.22 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
#import bibtexparser
import pandas as pd
import os
import nltk
from nltk.corpus import stopwords
import re
nltk.download('stopwords')
nltk.download('punkt')
# stopwords.words("english")[:10]
colnames = ['title','keywords','abstract','label']
def preprocess_text(text: str, remove_stopwords: bool) -> str:
"""This utility function sanitizes a string by:
- removing links
- removing special characters
- removing numbers
- removing stopwords
- transforming in lowercase
- removing excessive whitespaces
Args:
text (str): the input text you want to clean
remove_stopwords (bool): whether or not to remove stopwords
Returns:
str: the cleaned text
"""
# remove links
text = re.sub(r"http\S+", "", text)
# remove special chars and numbers
text = re.sub("[^A-Za-z0-9]+", " ", text)
# remove stopwords
if remove_stopwords:
# 1. tokenize
tokens = nltk.word_tokenize(text)
# 2. check if stopword
tokens = [w for w in tokens if not w.lower() in stopwords.words("english")]
# 3. join back together
text = " ".join(tokens)
# return text in lower case and stripped of whitespaces
text = text.lower().strip()
return text
# def convert_bib_tocsv(bibfilename, csvfilename):
# with open(bibfilename) as bibtex_file:
# bib_database = bibtexparser.load(bibtex_file)
# bibdf = pd.DataFrame(bib_database.entries)
# bibdf.to_csv(csvfilename, index=False)
def tf_idf_processing(data):
data['cleaned'] = data['Title_Abstract'].apply(lambda x: preprocess_text(x, remove_stopwords=True))
return data
def clean_data(data):
data = data.drop_duplicates(subset=["title"])
data = data.drop_duplicates(subset=["abstract"])
indexnames = data[data['abstract'] == "[No abstract available]"].index
data.drop(labels=indexnames,inplace=True)
return data
def datahandler(datapath):
file_path = datapath
if os.path.isfile(file_path) and file_path.endswith('.csv'):
data = pd.read_csv(file_path,encoding='unicode_escape',usecols=['title','keywords','abstract','label'])
data.columns = colnames
data = clean_data(data)
return data