-
Notifications
You must be signed in to change notification settings - Fork 0
/
sumuraizer.py
62 lines (45 loc) · 1.83 KB
/
sumuraizer.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
import argparse
from collections import Counter
import re
from scraper import scrape
def main():
parser = argparse.ArgumentParser(description='Summarize a document from a file, or the command line if no file is provided.')
parser.add_argument('location', metavar='location', type=str, nargs='?',
help='location of the document file')
parser.add_argument('--url', dest='url', action='store_true',
default=False,
help='pull an article from the web (default: from filesystem)')
args = parser.parse_args()
# print(args)
title, text = "", ""
if args.location:
if args.url:
title, text = scrape(args.location)
else:
with open(args.location, "r") as file:
raw_text = file.read()
title = raw_text.split('\n')[0]
text = raw_text
# [^(Mr)(Mrs)(Ms)(Dr)(M)(Prof)]
else:
title = input("Article Title:\n")
text = input("Article Text:\n")
# print("%s\n%s" % (title, text))
def rank_sentence(sentence, bow):
words = [special_chars.sub("", word) for word in re.split('\s+', sentence)]
# print(words, sum([bow[word] for word in words]))
return -sum([bow[word] for word in words])
sentences = re.split('((?<=\.|\!|\?)\s|(?<=\.\")\s)', text)
special_chars = re.compile('[^A-Za-z0-9]')
bag_of_words = Counter([special_chars.sub("", word) for word in re.split('\s+', text)])
# print(bag_of_words)
ranked_sentences = sorted(sentences,
key = lambda sentence: rank_sentence(sentence, bag_of_words))
num_sentences = min(int(len(sentences) ** 0.5), len(sentences))
print(num_sentences)
top_sentences = ranked_sentences[:num_sentences]
ordered_sentences = dict(zip(sentences, range(len(sentences))))
top_sentences = sorted(top_sentences, key = lambda sentence: ordered_sentences[sentence])
print('\n'.join(top_sentences))
if __name__ == "__main__":
main()