-
Notifications
You must be signed in to change notification settings - Fork 0
/
words_from_sentences.py
56 lines (46 loc) · 1.62 KB
/
words_from_sentences.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
import re
import argparse
parser = argparse.ArgumentParser()
def parse_args():
parser.add_argument("-f", "--file", help="path to text file")
return parser.parse_args()
def remove_punctuation(word):
salutation = re.match('((Mr|Mrs|Ms|Dr|Sr|[A-Z])\.|\w\.\w\.)', word)
str_with_hyp = re.match('\w+(?:-\w+)+', word)
str_with_amp = re.match('\w+(?:&\w+)+', word)
str_with_single_quote = re.match('\w+\'[a-z]', word)
if salutation is not None:
return word
elif str_with_hyp is not None:
return word
elif str_with_amp is not None:
return word
elif str_with_single_quote is not None:
return word
else:
return (re.sub('[^A-Za-z0-9]+', '', word))
def find_words(word, sentences):
line_numbers = []
for i in range(len(sentences)):
if word in sentences[i]:
line_numbers.append(i+1)
return line_numbers
def main():
# data = input()
args = parse_args()
sentence_pattern = re.compile(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\!|\?)\s')
seen = {}
sentences = []
with open(args.file) as f:
data = f.readlines()
for sentence in re.split(sentence_pattern, str(data)):
sentences.append(sentence)
print("Sentence {} : {}".format(len(sentences),sentence))
for word in re.split(r'\s', ' '.join(data)):
stripped_word = remove_punctuation(word)
if stripped_word not in seen:
seen[stripped_word] = find_words(stripped_word, sentences)
for key,value in seen.items():
print("{}: {}".format(key, ','.join(str(i) for i in value) ))
if __name__ == '__main__':
main()