forked from Santi871/sherlock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit_user.py
2001 lines (1730 loc) · 67 KB
/
reddit_user.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import csv
import datetime
import re
import json
import time
import sys
import calendar
from collections import Counter
from itertools import groupby
from urllib.parse import urlparse
import requests
import pytz
from subreddits import subreddits_dict, ignore_text_subs, default_subs
from text_parser import TextParser
parser = TextParser()
class UserNotFoundError(Exception):
pass
class NoDataError(Exception):
pass
class Util:
"""
Contains a collection of common utility methods.
"""
@staticmethod
def sanitize_text(text):
"""
Returns text after removing unnecessary parts.
"""
MAX_WORD_LENGTH = 1024
_text = " ".join([
l for l in text.decode('ascii').strip().split("\n") if (
not l.strip().startswith(">")
)
])
substitutions = [
(r"\[(.*?)\]\((.*?)\)", r""), # Remove links from Markdown
(r"[\"](.*?)[\"]", r""), # Remove text within quotes
(r" \'(.*?)\ '", r""), # Remove text within quotes
(r"\.+", r". "), # Remove ellipses
(r"\(.*?\)", r""), # Remove text within round brackets
(r"&", r"&"), # Decode HTML entities
(r"http.?:\S+\b", r" ") # Remove URLs
]
for pattern, replacement in substitutions:
_text = re.sub(pattern, replacement, _text, flags=re.I)
# Remove very long words
_text = " ".join(
[word for word in _text.split(" ") if len(word) <= MAX_WORD_LENGTH]
)
return _text
@staticmethod
def coalesce(l):
"""
Given a list, returns the last element that is not equal to "generic".
"""
l = [x for x in l if x.lower() != "generic"]
return next(iter(l[::-1]), "")
@staticmethod
def humanize_days(days):
"""
Return text with years, months and days given number of days.
"""
y = days/365 if days > 365 else 0
m = (days - y*365)/31 if days > 30 else 0
d = (days - m*31 - y*365)
yy = str(y) + " year" if y else ""
if y > 1:
yy += "s"
mm = str(m) + " month" if m else ""
if m > 1:
mm += "s"
dd = str(d) + " day"
if d>1 or d==0:
dd += "s"
return (yy + " " + mm + " " + dd).strip()
@staticmethod
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return ((val - src[0])/(src[1] - src[0])) * (dst[1]-dst[0]) + dst[0]
# Base class for comments and submissions
class Post(object):
"""
A class for "posts" - a post can either be a submission or a comment.
"""
def __init__(
self, id, subreddit, text, created_utc, score, permalink, gilded
):
# Post id
self.id = id
# Subreddit in which this comment or submission was posted
self.subreddit = subreddit
# For comments, the comment body and for submissions, the self-text
self.text = text
# UTC timestamp when post was created
self.created_utc = created_utc
# Post score
self.score = score
# Permalink to post
self.permalink = permalink
# Gilded
self.gilded = gilded
class Comment(Post):
"""
A class for comments derived from Post.
"""
def __init__(
self, id, subreddit, text, created_utc, score,
permalink, submission_id, edited, top_level, gilded
):
super(Comment, self).__init__(
id, subreddit, text, created_utc, score, permalink, gilded
)
# Link ID where comment was posted
self.submission_id = submission_id
# Edited flag
self.edited = edited
# Top-level flag
self.top_level = top_level
class Submission(Post):
"""
A class for submissions derived from Post.
"""
def __init__(
self, id, subreddit, text, created_utc, score,
permalink, url, title, is_self, gilded, domain
):
super(Submission, self).__init__(
id, subreddit, text, created_utc, score, permalink, gilded
)
# Submission link URL
self.url = url
# Submission title
self.title = title
# Self post?
self.is_self = is_self
# Domain
self.domain = domain
class RedditUser:
"""
Models a redditor object. Contains methods for processing
comments and submissions.
"""
# If user has posted in a sub 3 times or more, they are
# probably interested in the topic.
MIN_THRESHOLD = 3
MIN_THRESHOLD_FOR_DEFAULT = 10
HEADERS = {
'User-Agent': 'Sherlock v0.1 by /u/orionmelt'
}
IMAGE_DOMAINS = ["imgur.com", "flickr.com"]
VIDEO_DOMAINS = ["youtube.com", "youtu.be", "vimeo.com", "liveleak.com"]
IMAGE_EXTENSIONS = ["jpg", "png", "gif", "bmp"]
def __init__(self, username, json_data=None):
# Populate username and about data
self.username = username
self.comments = []
self.submissions = []
if not json_data:
# Retrieve about
self.about = self.get_about()
if not self.about:
raise UserNotFoundError
# Retrieve comments and submissions
self.comments = self.get_comments()
self.submissions = self.get_submissions()
else:
data = json.loads(json_data)
self.about = {
"created_utc" : datetime.datetime.fromtimestamp(
data["about"]["created_utc"], tz=pytz.utc
),
"link_karma" : data["about"]["link_karma"],
"comment_karma" : data["about"]["comment_karma"],
"name" : data["about"]["name"],
"reddit_id" : data["about"]["id"],
"is_mod" : data["about"]["is_mod"]
}
for c in data["comments"]:
self.comments.append(
Comment(
id=c["id"],
subreddit=c["subreddit"],
text=c["text"],
created_utc=c["created_utc"],
score=c["score"],
permalink=c["permalink"],
submission_id=c["submission_id"],
edited=c["edited"],
top_level=c["top_level"],
gilded=c["gilded"]
)
)
for s in data["submissions"]:
self.submissions.append(
Submission(
id=s["id"],
subreddit=s["subreddit"],
text=s["text"],
created_utc=s["created_utc"],
score=s["score"],
permalink=s["permalink"],
url=s["url"],
title=s["title"],
is_self=s["is_self"],
gilded=s["gilded"],
domain=s["domain"]
)
)
self.username = self.about["name"]
self.signup_date = self.about["created_utc"]
self.link_karma = self.about["link_karma"]
self.comment_karma = self.about["comment_karma"]
self.reddit_id = self.about["reddit_id"]
self.is_mod = self.about["is_mod"]
# Initialize other properties
self.today = datetime.datetime.now(tz=pytz.utc).date()
start = self.signup_date.date()
self.age_in_days = (self.today - start).days
self.first_post_date = None
self.earliest_comment = None
self.latest_comment = None
self.best_comment = None
self.worst_comment = None
self.earliest_submission = None
self.latest_submission = None
self.best_submission = None
self.worst_submission = None
self.metrics = {
"date" : [],
"weekday" : [],
"hour" : [],
"subreddit" : [],
"heatmap" : [],
"recent_karma" : [],
"recent_posts" : []
}
self.submissions_by_type = {
"name" : "All",
"children" : [
{
"name" : "Self",
"children" : []
},
{
"name" : "Image",
"children" : []
},
{
"name" : "Video",
"children" : []
},
{
"name" : "Other",
"children" : []
}
]
}
self.metrics["date"] = [
{
"date" : (year, month),
"comments" : 0,
"submissions": 0,
"comment_karma": 0,
"submission_karma": 0
} for (year, month) in sorted(
list(
set([
(
(self.today - datetime.timedelta(days=x)).year,
(self.today - datetime.timedelta(days=x)).month
) for x in range(0, (self.today - start).days)
])
)
)
]
self.metrics["heatmap"] = [0] * 24 * 61
self.metrics["recent_karma"] = [0] * 61
self.metrics["recent_posts"] = [0] * 61
self.metrics["hour"] = [
{
"hour": hour,
"comments": 0,
"submissions": 0,
"comment_karma": 0,
"submission_karma": 0
} for hour in range(0, 24)
]
self.metrics["weekday"] = [
{
"weekday": weekday,
"comments": 0,
"submissions": 0,
"comment_karma": 0,
"submission_karma": 0
} for weekday in range(0, 7)
]
self.genders = []
self.orientations = []
self.relationship_partners = []
# Data that we are reasonably sure that *are* names of places.
self.places_lived = []
# Data that looks like it could be a place, but we're not sure.
self.places_lived_extra = []
# Data that we are reasonably sure that *are* names of places.
self.places_grew_up = []
# Data that looks like it could be a place, but we're not sure.
self.places_grew_up_extra = []
self.family_members = []
self.pets = []
self.attributes = []
self.attributes_extra = []
self.possessions = []
self.possessions_extra = []
self.actions = []
self.actions_extra = []
self.favorites = []
self.sentiments = []
self.derived_attributes = {
"family_members" : [],
"gadget" : [],
"gender" : [],
"locations" : [],
"orientation" : [],
"physical_characteristics" : [],
"political_view" : [],
"possessions" : [],
"religion and spirituality" : []
}
self.corpus = ""
self.commented_dates = []
self.submitted_dates = []
self.lurk_period = None
self.comments_gilded = 0
self.submissions_gilded = 0
self.process()
def __str__(self):
return str(self.results())
def get_about(self):
"""
Returns basic data about redditor.
"""
url = r"http://www.reddit.com/user/%s/about.json" % self.username
response = requests.get(url, headers=self.HEADERS)
response_json = response.json()
if "error" in response_json and response_json["error"] == 404:
return None
about = {
"created_utc" : datetime.datetime.fromtimestamp(
response_json["data"]["created_utc"], tz=pytz.utc
),
"link_karma" : response_json["data"]["link_karma"],
"comment_karma" : response_json["data"]["comment_karma"],
"name" : response_json["data"]["name"],
"reddit_id" : response_json["data"]["id"],
"is_mod" : response_json["data"]["is_mod"]
}
return about
def get_comments(self, limit=None):
"""
Returns a list of redditor's comments.
"""
comments = []
more_comments = True
after = None
base_url = r"http://www.reddit.com/user/%s/comments/.json?limit=100" \
% self.username
url = base_url
while more_comments:
response = requests.get(url, headers=self.HEADERS)
response_json = response.json()
# TODO - Error handling for user not found (404) and
# rate limiting (429) errors
for child in response_json["data"]["children"]:
id = child["data"]["id"].encode("ascii", "ignore")
subreddit = child["data"]["subreddit"].\
encode("ascii", "ignore")
text = child["data"]["body"].encode("ascii", "ignore")
created_utc = child["data"]["created_utc"]
score = child["data"]["score"]
submission_id = child["data"]["link_id"].\
encode("ascii", "ignore").lower()[3:]
edited = child["data"]["edited"]
top_level = True \
if child["data"]["parent_id"].startswith("t3") else False
gilded = child["data"]["gilded"]
permalink = "http://www.reddit.com/r/%s/comments/%s/_/%s" \
% (subreddit, submission_id, id)
comment = Comment(
id=id,
subreddit=subreddit,
text=text,
created_utc=created_utc,
score=score,
permalink=permalink,
submission_id=submission_id,
edited=edited,
top_level=top_level,
gilded=gilded
)
comments.append(comment)
after = response_json["data"]["after"]
if after:
url = base_url + "&after=%s" % after
# reddit may rate limit if we don't wait for 2 seconds
# between successive requests. If that happens,
# uncomment and increase sleep time in the following line.
#time.sleep(0.5)
else:
more_comments = False
return comments
def get_submissions(self, limit=None):
"""
Returns a list of redditor's submissions.
"""
submissions = []
more_submissions = True
after = None
base_url = r"http://www.reddit.com/user/%s/submitted/.json?limit=100" \
% self.username
url = base_url
while more_submissions:
response = requests.get(url, headers=self.HEADERS)
response_json = response.json()
# TODO - Error handling for user not found (404) and
# rate limiting (429) errors
for child in response_json["data"]["children"]:
id = child["data"]["id"].encode("ascii","ignore")
subreddit = child["data"]["subreddit"].\
encode("ascii", "ignore")
text = child["data"]["selftext"].\
encode("ascii", "ignore").lower()
created_utc = child["data"]["created_utc"]
score = child["data"]["score"]
permalink = "http://www.reddit.com" + \
child["data"]["permalink"].lower()
url = child["data"]["url"].lower()
title = child["data"]["title"]
is_self = child["data"]["is_self"]
gilded = child["data"]["gilded"]
domain = child["data"]["domain"]
submission = Submission(
id=id,
subreddit=subreddit,
text=text,
created_utc=created_utc,
score=score,
permalink=permalink,
url=url,
title=title,
is_self=is_self,
gilded=gilded,
domain=domain
)
submissions.append(submission)
after = response_json["data"]["after"]
if after:
url = base_url + "&after=%s" % after
# reddit may rate limit if we don't wait for 2 seconds
# between successive requests. If that happens,
# uncomment and increase sleep time in the following line.
time.sleep(2)
else:
more_submissions = False
return submissions
def process(self):
"""
Retrieves redditor's comments and submissions and
processes each of them.
"""
if self.comments:
self.process_comments()
if self.submissions:
self.process_submissions()
if self.comments or self.submissions:
self.derive_attributes()
def process_comments(self):
"""
Process list of redditor's comments.
"""
if not self.comments:
return
self.earliest_comment = self.comments[-1]
self.latest_comment = self.comments[0]
self.best_comment = self.comments[0]
self.worst_comment = self.comments[0]
for comment in self.comments:
self.process_comment(comment)
def process_submissions(self):
"""
Process list of redditor's submissions.
"""
if not self.submissions:
return
self.earliest_submission = self.submissions[-1]
self.latest_submission = self.submissions[0]
self.best_submission = self.submissions[0]
self.worst_submission = self.submissions[0]
for submission in self.submissions:
self.process_submission(submission)
def process_comment(self, comment):
"""
Process a single comment.
* Updates metrics
* Sanitizes and extracts chunks from comment.
"""
# Sanitize comment text.
text = Util.sanitize_text(comment.text)
# Add comment text to corpus.
self.corpus += text.lower()
comment_timestamp = datetime.datetime.fromtimestamp(
comment.created_utc, tz=pytz.utc
)
self.commented_dates.append(comment_timestamp)
self.comments_gilded += comment.gilded
days_ago_60 = self.today - datetime.timedelta(60)
if (comment_timestamp.date() - days_ago_60).days > 0:
self.metrics["heatmap"][
(comment_timestamp.date() - days_ago_60).days*24 + \
comment_timestamp.hour
] += 1
self.metrics["recent_karma"][
(comment_timestamp.date() - days_ago_60).days
] += comment.score
self.metrics["recent_posts"][
(comment_timestamp.date() - days_ago_60).days
] += 1
# Update metrics
for i, d in enumerate(self.metrics["date"]):
if d["date"] == (
comment_timestamp.date().year,
comment_timestamp.date().month
):
d["comments"] += 1
d["comment_karma"] += comment.score
self.metrics["date"][i] = d
break
for i, h in enumerate(self.metrics["hour"]):
if h["hour"] == comment_timestamp.hour:
h["comments"] += 1
h["comment_karma"] += comment.score
self.metrics["hour"][i] = h
break
for i, w in enumerate(self.metrics["weekday"]):
if w["weekday"] == comment_timestamp.date().weekday():
w["comments"] += 1
w["comment_karma"] += comment.score
self.metrics["weekday"][i] = w
break
if comment.score > self.best_comment.score:
self.best_comment = comment
elif comment.score < self.worst_comment.score:
self.worst_comment = comment
# If comment is in a subreddit in which comments/self text
# are to be ignored (such as /r/jokes, /r/writingprompts, etc),
# do not process it further.
if comment.subreddit in ignore_text_subs:
return False
# If comment text does not contain "I" or "my", why even bother?
if not re.search(r"\b(i|my)\b", text, re.I):
return False
# Now, this is a comment that needs to be processed.
(chunks, sentiments) = parser.extract_chunks(text)
self.sentiments += sentiments
for chunk in chunks:
self.load_attributes(chunk, comment)
return True
def process_submission(self, submission):
"""
Process a single submission.
* Updates metrics
* Sanitizes and extracts chunks from self text.
"""
if(submission.is_self):
text = Util.sanitize_text(submission.text)
self.corpus += text.lower()
submission_timestamp = datetime.datetime.fromtimestamp(
submission.created_utc, tz=pytz.utc
)
self.submitted_dates.append(submission_timestamp)
self.submissions_gilded += submission.gilded
days_ago_60 = self.today - datetime.timedelta(60)
if (submission_timestamp.date() - days_ago_60).days>0:
self.metrics["heatmap"][
((submission_timestamp.date() - days_ago_60).days-1)*24 + \
submission_timestamp.hour
] += 1
self.metrics["recent_karma"][
(submission_timestamp.date() - days_ago_60).days
] += submission.score
self.metrics["recent_posts"][
(submission_timestamp.date() - days_ago_60).days
] += 1
for i, d in enumerate(self.metrics["date"]):
if d["date"] == (
submission_timestamp.date().year,
submission_timestamp.date().month
):
d["submissions"] += 1
d["submission_karma"] += submission.score
self.metrics["date"][i] = d
break
for i, h in enumerate(self.metrics["hour"]):
if h["hour"] == submission_timestamp.hour:
h["submissions"] += 1
h["submission_karma"] += submission.score
self.metrics["hour"][i] = h
break
for i, w in enumerate(self.metrics["weekday"]):
if w["weekday"] == submission_timestamp.date().weekday():
w["submissions"] += 1
w["submission_karma"] += submission.score
self.metrics["weekday"][i] = w
break
submission_type = None
submission_domain = None
submission_url_path = urlparse(submission.url).path
if submission.domain.startswith("self."):
submission_type = "Self"
submission_domain = submission.subreddit
elif (
submission_url_path.endswith(tuple(self.IMAGE_EXTENSIONS)) or
submission.domain.endswith(tuple(self.IMAGE_DOMAINS))
):
submission_type = "Image"
submission_domain = submission.domain
elif submission.domain.endswith(tuple(self.VIDEO_DOMAINS)):
submission_type = "Video"
submission_domain = submission.domain
else:
submission_type = "Other"
submission_domain = submission.domain
t = [
x for x in self.submissions_by_type["children"] \
if x["name"]==submission_type
][0]
d = (
[x for x in t["children"] if x["name"]==submission_domain] or \
[None]
)[0]
if d:
d["size"] += 1
else:
t["children"].append({
"name" : submission_domain,
"size" : 1
})
if submission.score > self.best_submission.score:
self.best_submission = submission
elif submission.score < self.worst_submission.score:
self.worst_submission = submission
# If submission is in a subreddit in which comments/self text
# are to be ignored (such as /r/jokes, /r/writingprompts, etc),
# do not process it further.
if submission.subreddit in ignore_text_subs:
return False
# Only process self texts that contain "I" or "my"
if not submission.is_self or not re.search(r"\b(i|my)\b",text,re.I):
return False
(chunks, sentiments) = parser.extract_chunks(text)
self.sentiments += sentiments
for chunk in chunks:
self.load_attributes(chunk, submission)
return True
def load_attributes(self, chunk, post):
"""
Given an extracted chunk, load appropriate attribtues from it.
"""
# Is this chunk a possession/belonging?
if chunk["kind"] == "possession" and chunk["noun_phrase"]:
# Extract noun from chunk
noun_phrase = chunk["noun_phrase"]
noun_phrase_text = " ".join([w for w, t in noun_phrase])
norm_nouns = " ".join([
parser.normalize(w, t) \
for w,t in noun_phrase if t.startswith("N")
])
noun = next(
(w for w, t in noun_phrase if t.startswith("N")), None
)
if noun:
# See if noun is a pet, family member or a relationship partner
pet = parser.pet_animal(noun)
family_member = parser.family_member(noun)
relationship_partner = parser.relationship_partner(noun)
if pet:
self.pets.append((pet, post.permalink))
elif family_member:
self.family_members.append((family_member, post.permalink))
elif relationship_partner:
self.relationship_partners.append(
(relationship_partner, post.permalink)
)
else:
self.possessions_extra.append((norm_nouns, post.permalink))
# Is this chunk an action?
elif chunk["kind"] == "action" and chunk["verb_phrase"]:
verb_phrase = chunk["verb_phrase"]
verb_phrase_text = " ".join([w for w, t in verb_phrase])
# Extract verbs, adverbs, etc from chunk
norm_adverbs = [
parser.normalize(w,t) \
for w, t in verb_phrase if t.startswith("RB")
]
adverbs = [w.lower() for w, t in verb_phrase if t.startswith("RB")]
norm_verbs = [
parser.normalize(w,t) \
for w, t in verb_phrase if t.startswith("V")
]
verbs = [w.lower() for w, t in verb_phrase if t.startswith("V")]
prepositions = [w for w, t in chunk["prepositions"]]
noun_phrase = chunk["noun_phrase"]
noun_phrase_text = " ".join(
[w for w, t in noun_phrase if t not in ["DT"]]
)
norm_nouns = [
parser.normalize(w,t) \
for w, t in noun_phrase if t.startswith("N")
]
proper_nouns = [w for w, t in noun_phrase if t == "NNP"]
determiners = [
parser.normalize(w, t) \
for w, t in noun_phrase if t.startswith("DT")
]
prep_noun_phrase = chunk["prep_noun_phrase"]
prep_noun_phrase_text = " ".join([w for w, t in prep_noun_phrase])
pnp_prepositions = [
w.lower() for w, t in prep_noun_phrase if t in ["TO", "IN"]
]
pnp_norm_nouns = [
parser.normalize(w, t) \
for w, t in prep_noun_phrase if t.startswith("N")
]
pnp_determiners = [
parser.normalize(w, t) \
for w, t in prep_noun_phrase if t.startswith("DT")
]
full_noun_phrase = (
noun_phrase_text + " " + prep_noun_phrase_text
).strip()
# TODO - Handle negative actions (such as I am not...),
# but for now:
if any(
w in ["never", "no", "not", "nothing"] \
for w in norm_adverbs+determiners
):
return
# I am/was ...
if (len(norm_verbs) == 1 and "be" in norm_verbs and
not prepositions and noun_phrase):
# Ignore gerund nouns for now
if (
"am" in verbs and
any(n.endswith("ing") for n in norm_nouns)
):
self.attributes_extra.append(
(full_noun_phrase, post.permalink)
)
return
attribute = []
for noun in norm_nouns:
gender = None
orientation = None
if "am" in verbs:
gender = parser.gender(noun)
orientation = parser.orientation(noun)
if gender:
self.genders.append((gender, post.permalink))
elif orientation:
self.orientations.append(
(orientation, post.permalink)
)
# Include only "am" phrases
elif "am" in verbs:
attribute.append(noun)
if attribute and (
(
# Include only attributes that end
# in predefined list of endings...
any(
a.endswith(
parser.include_attribute_endings
) for a in attribute
) and not (
# And exclude...
# ...certain lone attributes
(
len(attribute) == 1 and
attribute[0] in parser.skip_lone_attributes and
not pnp_norm_nouns
)
or
# ...predefined skip attributes
any(a in attribute for a in parser.skip_attributes)
or
# ...attributes that end in predefined
# list of endings
any(
a.endswith(
parser.exclude_attribute_endings
) for a in attribute
)
)
) or
(
# And include special attributes with different endings
any(a in attribute for a in parser.include_attributes)
)
):
self.attributes.append(
(full_noun_phrase, post.permalink)
)
elif attribute:
self.attributes_extra.append(
(full_noun_phrase, post.permalink)
)
# I live(d) in ...
elif "live" in norm_verbs and prepositions and norm_nouns:
if any(
p in ["in", "near", "by"] for p in prepositions
) and proper_nouns:
self.places_lived.append(
(
" ".join(prepositions) + " " + noun_phrase_text,
post.permalink
)
)
else: