-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathner.py
66 lines (45 loc) · 1.39 KB
/
ner.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
# Robin Camille Davis
# CODEX 2016
# Top 5 names from a .txt file
##This script asks for the URL to a plain-text file (Project Gutenberg).
##It outputs the top 5 person names from the text using the
##Stanford Named Entity Recognition interface in NLTK.
##
##Caveats: first/last names and honorifics not considered
import urllib2
from nltk import tree
from nltk import word_tokenize as tok
from nltk import pos_tag as postag
from nltk import ne_chunk as ne
from nltk.corpus import gutenberg as gb
from collections import Counter
theurl = raw_input("URL to .txt file: ")
sourcefile = urllib2.urlopen(theurl)
source = sourcefile.read()
#Tokenize
sourcetok = tok(source)
#Tag POS
sourcetag = postag(sourcetok)
#Outputs POS-tagged text
sourcene = ne(sourcetag, binary=False)
charsall = []
for n in sourcene:
if type(n) == tree.Tree:
if n.label() == 'PERSON':
for m in n:
charsall.append(m[0])
honorifics = ['Mr.', 'Mrs.', 'Ms.', 'Miss', 'Dr.', 'Prof.', 'Professor', 'Lord', 'Lady', 'Sir', 'Madam', 'Dame', 'Rev.', 'Rabbi']
charsallnames = []
for s in charsall:
if s in honorifics:
pass
else:
charsallnames.append(s)
counted = (word for word in charsallnames if word[:1].isupper())
c = Counter(counted)
charscommon = c.most_common(5)
chars = []
for s in charscommon:
chars.append(s[0])
print '\nMost common names:'
print '\t'.join(chars)