-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
65 lines (55 loc) · 2.05 KB
/
main.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
"""
Python wrapper for the website: https://www.homophone.com/
Gets the homophones of a word.
"""
from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
from typing import Dict, List
import re
class Pyphones:
def __init__(self, word):
self.word = word
self.url = "https://www.homophone.com/search?page={}&type=&q={}"
self.homophones = {self.word: []}
def get_the_page(self, page_no=1):
"""
Get the page content.
Returns
str: the content of the page.
"""
url = self.url.format(page_no, self.word)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
return soup
def get_the_page_nos(self):
"""
Get the total number of pages
Returns
int: the total number of the pages.
"""
soup = self.get_the_page()
pages = soup.find_all('div', attrs={'class':'col-sm-9'})
total_pages = pages[0].find('h5').text.split('/')[-1].strip()
return int(total_pages)
def get_the_homophones(self):
"""
Get the homophones of the word.
Returns
dict: {word: [list_of_homophones]} against each word.
"""
total_pages = self.get_the_page_nos()
for ix in range(total_pages):
page_no = ix + 1
soup = self.get_the_page(page_no)
raw_homophones = soup.find_all('div', attrs={'class': 'well well-lg'})
for elem in range(len(raw_homophones)):
raw_homophones_2 = raw_homophones[elem].find_all('a', attrs={'class': 'btn word-btn'})
list_of_homophones = list(raw_homophones_2)
if any(list_of_homophones):
local_homophones = []
for tag_of_homophone in list_of_homophones:
homophone = tag_of_homophone.text
local_homophones.append(homophone)
self.homophones[self.word].append(local_homophones)
return self.homophones