|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +"""pointofview - A Python package for determining a piece of text's point of view (first, second, third, or unknown).""" |
| 4 | + |
| 5 | +import re |
| 6 | + |
| 7 | +import pkg_resources |
| 8 | + |
| 9 | +__version__ = pkg_resources.resource_string( |
| 10 | + 'pointofview', 'VERSION').decode('utf-8').strip() |
| 11 | + |
| 12 | +POV_WORDS = { |
| 13 | + 'first': |
| 14 | + ["i", "i'm", "i'll", "i'd", "i've", "me", "mine", "myself", "we", |
| 15 | + "we're", "we'll", "we'd", "we've", "us", "ours", "ourselves"], |
| 16 | + 'second': |
| 17 | + ["you", "you're", "you'll", "you'd", "you've", |
| 18 | + "your", "yours", "yourself", "yourselves"], |
| 19 | + 'third': |
| 20 | + ["he", "he's", "he'll", "he'd", "him", "his", "himself", "she", "she's", |
| 21 | + "she'll", "she'd", "her", "hers", "herself", "it", "it's", "it'll", |
| 22 | + "it'd", "itself", "they", "they're", "they'll", "they'd", "they've", |
| 23 | + "them", "their", "theirs", "themselves"] |
| 24 | +} |
| 25 | + |
| 26 | +RE_WORDS = re.compile(r"[^\w’']+") |
| 27 | + |
| 28 | + |
| 29 | +def _normalize_word(word): |
| 30 | + return word.strip().lower().replace("’", "'") |
| 31 | + |
| 32 | + |
| 33 | +def get_word_pov(word): |
| 34 | + for pov in POV_WORDS: |
| 35 | + if _normalize_word(word) in POV_WORDS[pov]: |
| 36 | + return pov |
| 37 | + return None |
| 38 | + |
| 39 | + |
| 40 | +def parse_pov_words(text): |
| 41 | + pov_words = { |
| 42 | + 'first': [], |
| 43 | + 'second': [], |
| 44 | + 'third': [], |
| 45 | + } |
| 46 | + words = re.split(RE_WORDS, text.strip().lower()) |
| 47 | + for word in words: |
| 48 | + pov = get_word_pov(word) |
| 49 | + if pov != None: |
| 50 | + pov_words[pov].append(word) |
| 51 | + return pov_words |
| 52 | + |
| 53 | + |
| 54 | +def get_pov(text): |
| 55 | + pov_words = parse_pov_words(text) |
| 56 | + if len(pov_words['first']) > 0: |
| 57 | + return 'first' |
| 58 | + elif len(pov_words['second']) > 0: |
| 59 | + return 'second' |
| 60 | + elif len(pov_words['third']) > 0: |
| 61 | + return 'third' |
| 62 | + else: |
| 63 | + return None |
0 commit comments