-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
98 lines (75 loc) · 2.71 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
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
#!/usr/bin/env python3
"""
Creator: VPR
Created: November 20, 2021
Modified: November 20, 2021
Brief:
This is a web scraping utility that pulls data from worldatlas.com
and parses the table listed to extract a dictionary of the following
key/value pairs: 'State' : list_of_area_codes.
"""
import requests
import sys
from bs4 import BeautifulSoup
from argparse import ArgumentParser
from modules.scraper import parse_table
from modules.formatter import display_as_python_tuple, display_as_c_int_array
from typing import Union, NoReturn
source = "https://www.worldatlas.com/na/us/area-codes.html"
def handle_command_line() -> Union[NoReturn, None, str]:
argc = len(sys.argv)
if argc > 2:
__usage_error(1) # only specify one switch pls
parser = ArgumentParser()
parser.add_argument( "-c",
action="store_true",
dest="c",
help="Format the output as a const int array." )
parser.add_argument( "-cpp",
action="store_true",
dest="cpp",
help="Format the output as a const int array." )
parser.add_argument( "-py",
action="store_true",
dest="py",
help="Format the output as a tuple of ints." )
args = parser.parse_args()
if args.c == True:
return "c"
elif args.cpp == True:
return "cpp"
elif args.py == True:
return "py"
return None
def __usage_error(exit_code: int) -> NoReturn:
if exit_code == 1:
sys.stderr.write( f"Error: multiple switches selected.\n"
f"\n"
f"Usage:\n"
f" {sys.argv[0]} [ -c | -cpp | -py | -h | --help ]\n"
f"\n"
f"Example:\n"
f" {sys.argv[0]} -cpp\n"
f"\n" )
sys.stderr.write(f"Exited with exit code: {exit_code}.\n")
sys.exit(exit_code)
if __name__ == "__main__":
# Determine output language format
fmt = handle_command_line()
# Retrieving data from source
page = requests.get(source)
soup = BeautifulSoup(page.content, "html.parser")
# Select the main table
table = soup.find("table")
# Use this map as you see fit
area_codes_map = parse_table(table)
# Format based on user input
if fmt is None:
display_as_python_tuple(area_codes_map)
elif fmt == "c":
display_as_c_int_array(area_codes_map)
elif fmt == "cpp":
# TODO
display_as_c_int_array(area_codes_map)
elif fmt == "py":
display_as_python_tuple(area_codes_map)