-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNLP.py
214 lines (147 loc) · 6.05 KB
/
NLP.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# coding: utf-8
import urllib
import nltk
import rake_nltk
import requests
from bs4 import BeautifulSoup
# rake_nltk is the library needed for keyword extraction
from rake_nltk import Metric, Rake
import operator
from nltk.corpus import stopwords
set(stopwords.words('english'))
from nltk.tokenize import word_tokenize, sent_tokenize
# Synonyms e.g., mother, mom, and mommy should be treated the same way
# For this, use a Stemmer - an algorithm to bring words to its root word.
from nltk.stem import PorterStemmer
class NLP:
def __init__(self, html):
self.html = html
self.text = ''
self.title = ''
self.h1_tags = ''
# Create dictionary that will hold frequency of words in text - not including stop words
self.freqTable = dict()
# Stemmer (puts pluralized, tensed words/verbs into their root form eg: agreed -> agree, flies -> fli)
self.ps = PorterStemmer()
self.summary = ''
self.sentenceValue = dict()
self.stopWords = set(stopwords.words('english'))
self.createSummary()
def removeSpecialCharacters(self):
for char in self.text:
if char in " ?.!/;:":
self.text.replace(char,'')
def tally(self, words):
for word in words:
word = word.lower()
if word in self.stopWords:
continue
# Pass every word by the stemmer before adding it to our freqTable
# It is important to stem every word when going through each sentence before adding the score of the words in it.
word = self.ps.stem(word)
if word in self.freqTable:
self.freqTable[word] += 1
else:
self.freqTable[word] = 1
def clean(self):
self.beautifyText()
# Remove all special characters
self.removeSpecialCharacters()
def scoreSentences(self, sentences):
# Go through every sentence and give it a score depending on the words it has while also dividing the value by the
# length of the sentence to avoid giving more emphasis to longer sentences
for sentence in sentences:
sentence_length = len(sentence.split(' '))
for key,value in self.freqTable.items():
if key in sentence.lower():
if sentence[:12] in self.sentenceValue:
self.sentenceValue[sentence[:12]] += value / sentence_length
else:
self.sentenceValue[sentence[:12]] = value / sentence_length
def getAverageScore(self):
sumValues = 0
for sentence in self.sentenceValue:
sumValues += self.sentenceValue[sentence]
# Average value of a sentence from original text
return int(sumValues / len(self.sentenceValue))
def beautifyText(self):
soup = BeautifulSoup(self.html, "html.parser")
# Get all the text in <p> tags on the page
self.title = soup.title.text
self.h1_tags = soup.findAll("h1")
text = ''
h1_text = ''
p_tags = soup.findAll("p")
for r in p_tags:
tag = BeautifulSoup(str(r), "html.parser")
for a in tag.findAll('a'):
a.replaceWithChildren()
text = text + tag.text + '\n'
for h1 in self.h1_tags:
tag = BeautifulSoup(str(h1), "html.parser")
for a in tag.findAll('a'):
a.replaceWithChildren()
h1_text = h1_text + tag.text + '\n'
self.text = text
self.h1_text = h1_text
def createSummary(self):
try:
# Clean up the text
self.clean()
# Tokenize
words = word_tokenize(self.text)
# Tally occurrences into freqTable
self.tally(words)
# Sentence tokenize
sentences = sent_tokenize(self.text)
self.scoreSentences(sentences)
# What to compare each sentence's values to? The average of all the sentences
average = self.getAverageScore()
# Apply sentences in order into the summary
for sentence in sentences:
if sentence[:12] in self.sentenceValue and self.sentenceValue[sentence[:12]] > (1.5 * average):
self.summary += " " + sentence
except Exception as e:
print(str(e))
raise e
"""
# Test url:
#url = 'https://www.huffingtonpost.ca/entry/melania-trump-child-detainees_us_5b2bea31e4b0040e2740f172'
url = 'https://ca.reuters.com/article/topNews/idCAKCN1QI5JY-OCATP'
# Now that the main webpage text is extracted from the html, pass it to Rake to extract keywords
#r = Rake() # Uses stopwords for english from NLTK, and all puntuation characters.
#r.extract_keywords_from_text(text)
#r.get_ranked_phrases() # To get keyword phrases ranked highest to lowest.
# Extract all relevant text from page's html (ie try to avoid ads and other noise)
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
# Get all the text in <p> tags on the page
title = soup.title.text
h1_tags = soup.findAll("h1")
text = ''
h1_text = ''
p_tags = soup.findAll("p")
for r in p_tags:
tag = BeautifulSoup(str(r), "html.parser")
for a in tag.findAll('a'):
a.replaceWithChildren()
text = text + tag.text + '\n'
for h1 in h1_tags:
tag = BeautifulSoup(str(h1), "html.parser")
for a in tag.findAll('a'):
a.replaceWithChildren()
h1_text = h1_text + tag.text + '\n'
nlp = NLP(text)
"""
"""
#Test the stemmer on various pluralised words.
stemmer = PorterStemmer()
plurals = ['caresses', 'flies', 'dies', 'mules', 'denied','died', 'agreed', 'owned', 'humbled', 'sized','meeting',\
'stating', 'siezing', 'itemization','sensational', 'traditional', 'reference', 'colonizer','plotted']
singles = [stemmer.stem(plural) for plural in plurals]
print(' '.join(singles))
"""
# TODO:
# change language to be dynamic (in constructor)
# Want to report the authors of the article (if available)
# Want to ignore advertisements on pages where there are many