/
characterExtraction.py
232 lines (190 loc) · 7.13 KB
/
characterExtraction.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#! /usr/bin/env python2
"""
Filename: characterExtraction.py
Author: Emily Daniels
Date: April 2014
Purpose: Extracts character names from a text file and performs analysis of
text sentences containing the names.
"""
from collections import defaultdict
import json
import re
import nltk
from nltk.corpus import stopwords
from pattern.en import parse, Sentence, mood
from pattern.db import csv
from pattern.vector import Document, NB
# Download resources automatically if not installed
try:
nltk.data.find('corpora/stopwords')
except LookupError:
nltk.download('stopwords')
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
# https://github.com/clips/pattern/issues/295#issuecomment-841625057
try:
parse('dummy sentence')
except RuntimeError:
pass
def readText():
"""
Reads the text from a text file.
"""
with open("730.txt", "rb") as f:
text = f.read().decode('utf-8-sig')
return text
def chunkSentences(text):
"""
Parses text into parts of speech tagged with parts of speech labels.
Used for reference: https://gist.github.com/onyxfish/322906
"""
sentences = nltk.sent_tokenize(text)
tokenizedSentences = [nltk.word_tokenize(sentence)
for sentence in sentences]
taggedSentences = [nltk.pos_tag(sentence)
for sentence in tokenizedSentences]
if nltk.__version__[0:2] == "2.":
chunkedSentences = nltk.batch_ne_chunk(taggedSentences, binary=True)
else:
chunkedSentences = nltk.ne_chunk_sents(taggedSentences, binary=True)
return chunkedSentences
def extractEntityNames(tree, _entityNames=None):
"""
Creates a local list to hold nodes of tree passed through, extracting named
entities from the chunked sentences.
Used for reference: https://gist.github.com/onyxfish/322906
"""
if _entityNames is None:
_entityNames = []
try:
if nltk.__version__[0:2] == "2.":
label = tree.node
else:
label = tree.label()
except AttributeError:
pass
else:
if label == 'NE':
_entityNames.append(' '.join([child[0] for child in tree]))
else:
for child in tree:
extractEntityNames(child, _entityNames=_entityNames)
return _entityNames
def buildDict(chunkedSentences, _entityNames=None):
"""
Uses the global entity list, creating a new dictionary with the properties
extended by the local list, without overwriting.
Used for reference: https://gist.github.com/onyxfish/322906
"""
if _entityNames is None:
_entityNames = []
for tree in chunkedSentences:
extractEntityNames(tree, _entityNames=_entityNames)
return _entityNames
def removeStopwords(entityNames, customStopWords=None):
"""
Brings in stopwords and custom stopwords to filter mismatches out.
"""
# Memoize custom stop words
if customStopWords is None:
with open("customStopWords.txt", "rb") as f:
customStopwords = f.read().decode('utf-8-sig').split(', ')
for name in entityNames:
if name in stopwords.words('english') or name in customStopwords:
entityNames.remove(name)
def getMajorCharacters(entityNames):
"""
Adds names to the major character list if they appear frequently.
"""
return {name for name in entityNames if entityNames.count(name) > 10}
def splitIntoSentences(text):
"""
Split sentences on .?! "" and not on abbreviations of titles.
Used for reference: http://stackoverflow.com/a/8466725
"""
sentenceEnders = re.compile(r"""
# Split sentences on whitespace between them.
(?: # Group for two positive lookbehinds.
(?<=[.!?]) # Either an end of sentence punct,
| (?<=[.!?]['"]) # or end of sentence punct and quote.
) # End group of two positive lookbehinds.
(?<! Mr\. ) # Don't end sentence on "Mr."
(?<! Mrs\. ) # Don't end sentence on "Mrs."
(?<! Ms\. ) # Don't end sentence on "Ms."
(?<! Jr\. ) # Don't end sentence on "Jr."
(?<! Dr\. ) # Don't end sentence on "Dr."
(?<! Prof\. ) # Don't end sentence on "Prof."
(?<! Sr\. ) # Don't end sentence on "Sr."
\s+ # Split on whitespace between sentences.
""", re.IGNORECASE | re.VERBOSE)
return sentenceEnders.split(text)
def compareLists(sentenceList, majorCharacters):
"""
Compares the list of sentences with the character names and returns
sentences that include names.
"""
characterSentences = defaultdict(list)
for sentence in sentenceList:
for name in majorCharacters:
if re.search(r"\b(?=\w)%s\b(?!\w)" % re.escape(name),
sentence,
re.IGNORECASE):
characterSentences[name].append(sentence)
return characterSentences
def extractMood(characterSentences):
"""
Analyzes the sentence using grammatical mood module from pattern.
"""
characterMoods = defaultdict(list)
for key, value in characterSentences.items():
for x in value:
characterMoods[key].append(mood(Sentence(parse(str(x),
lemmata=True))))
return characterMoods
def extractSentiment(characterSentences):
"""
Trains a Naive Bayes classifier object with the reviews.csv file, analyzes
the sentence, and returns the tone.
"""
nb = NB()
characterTones = defaultdict(list)
for review, rating in csv("reviews.csv"):
nb.train(Document(review, type=int(rating), stopwords=True))
for key, value in characterSentences.items():
for x in value:
characterTones[key].append(nb.classify(str(x)))
return characterTones
def writeAnalysis(sentenceAnalysis):
"""
Writes the sentence analysis to a text file in the same directory.
"""
with open("sentenceAnalysis.txt", "wb") as f:
for item in sentenceAnalysis.items():
f.write("%s:%s\n" % item)
def writeToJSON(sentenceAnalysis):
"""
Writes the sentence analysis to a JSON file in the same directory.
"""
with open("sentenceAnalysis.json", "wb") as f:
json.dump(sentenceAnalysis, f)
if __name__ == "__main__":
text = readText()
chunkedSentences = chunkSentences(text)
entityNames = buildDict(chunkedSentences)
removeStopwords(entityNames)
majorCharacters = getMajorCharacters(entityNames)
sentenceList = splitIntoSentences(text)
characterSentences = compareLists(sentenceList, majorCharacters)
characterMoods = extractMood(characterSentences)
characterTones = extractSentiment(characterSentences)
# Merges sentences, moods and tones together into one dictionary on each
# character.
sentenceAnalysis = defaultdict(list,
[(k, [characterSentences[k],
characterTones[k],
characterMoods[k]])
for k in characterSentences])
writeAnalysis(sentenceAnalysis)
writeToJSON(sentenceAnalysis)