-
Notifications
You must be signed in to change notification settings - Fork 9
/
srapting_transcript_seasonwise.py
150 lines (111 loc) · 4.33 KB
/
srapting_transcript_seasonwise.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
import logging
import os
import re
import pickle
import pandas as pd
import requests
import threading
from bs4 import BeautifulSoup
class script():
def __init__(self):
self.response_folder = '~/Documents/Metis/project4'
self.response_folder = os.path.expanduser(self.response_folder)
self.main_character = ('phoebe:', 'rachel:', 'ross:', 'monica:', 'chandler:', 'joey:')
def scrapeData(self):
url="https://fangj.github.io/friends/"
soup = BeautifulSoup(requests.get(url).text, "lxml")
with open(os.path.join(self.response_folder, 'transcript_search_page.html'), 'wb') as fo:
fo.write(soup.prettify().encode('ascii', 'ignore'))
list_head = soup.find_all('li')
web_lst = [None]*len(list_head)
for i in range(len(list_head)):
episode = list_head[i].a.string
dict = {}
dict['episode']=episode
url = list_head[i].find('a', href=True).get('href')
dict['abs_url'] = str(f'https://fangj.github.io/friends/{url}')
web_lst[i] = dict
for i in range(len(list_head)):
url = web_lst[i]['abs_url']
soup = BeautifulSoup(requests.get(url).text, "lxml")
script = soup.find_all('p', align='left')
for s in script:
if s.text is None:
continue
try:
character = s.b.string
n = len(character)
if character not in web_lst[i]:
web_lst[i][character] = []
web_lst[i][character].append(s.text[n:])
except:
pass
def seasonNumber(self,lookup):
f = open(os.path.join(self.response_folder, 'FriendsScript.txt'), 'r')
for num, line in enumerate(f, 1):
if lookup in line:
print(lookup,'found at line:', num)
break
return num
def cleaningData(self,start,end):
f = open(os.path.join(self.response_folder, 'FriendsScript.txt'), 'r')
diag_dict = dict()
for i in range(6):
diag_dict[self.main_character[i]] = []
find_next = False
# index = 0
for i, line in enumerate(f): #maximum number of lines
if i<start or i>=end:
continue
line = line.strip('\n')
match = re.match(r'^([A-Z]\w+):', line)
if match:
name = match.group(0).lower()
if name in self.main_character:
find_next = True
diag = line.split(':')[1:]
diag_dict[name].append(diag)
name_prev = name
else:
if re.match('SEASON [A-z]*?', line):
find_next = False
elif re.match('SCENE [0-9]*?', line):
find_next = False
elif re.match('^[0-9]', line):
find_next = False
elif line in ['', '\r']:
find_next = False
elif find_next == True and re.match("[^[(]", line):
diag_dict[name_prev][-1].append(line)
# index += 1
return diag_dict
def writeOutput(self,diag_dict,filename,lookup):
diag_flat = {}
for char in self.main_character:
diag_flat[char] = {}
diag_flat[char]['diag'] = [word for sublist in diag_dict[char] for word in sublist]
diag_flat[char]['diag'] = ','.join(diag_flat[char]['diag'])
diag_flat[char]['season'] = lookup
# print(self.diag_flat['Rachel:'])
df_diag = pd.DataFrame.from_dict(diag_flat, orient='index')
# print(self.df_diag)
with open(os.path.join(self.response_folder, f'{filename}.pkl'), 'wb') as fo:
pickle.dump(df_diag, fo)
return diag_flat
def main():
diag = script()
print('Done Scipting')
start = 0
for i in range(2,12,1):
if i==11:
end = 117926
else:
extract = "Chapter " + str(i)
end = diag.seasonNumber(extract)
diag_dict = diag.cleaningData(start,end)
print('Done cleaning')
diag.writeOutput(diag_dict,f"chapter{i-1}",i)
print('Done')
start = end
if __name__ == "__main__":
main()