Skip to content

Instantly share code, notes, and snippets.

@cppxor2arr
Created March 22, 2018 13:39
Show Gist options
  • Save cppxor2arr/10a4d933ea9a64189da6fb70319ce4f5 to your computer and use it in GitHub Desktop.
Save cppxor2arr/10a4d933ea9a64189da6fb70319ce4f5 to your computer and use it in GitHub Desktop.
UD
#!/usr/bin/env python3
import sys, requests
from bs4 import BeautifulSoup
from random import choice
def main(argv):
if len(argv) < 2:
sys.exit("Invalid argument(s)\nSyntax: [optional: -n [n definition/examples]] [search term]")
if len(argv) > 3:
if argv[1] == "-n":
try:
n = float(argv[2])
except ValueError:
sys.exit("Invalid number")
else:
term = ' '.join(argv[3:])
else:
n = -1
term = ' '.join(argv[1:])
else:
n = -1
term = ' '.join(argv[1:])
show_term = False
if term == "-r":
page = requests.get("https://www.urbandictionary.com")
soup = BeautifulSoup(page.content, "html5lib")
term = choice(soup.find_all(class_ = "trending-link")).get_text()
show_term = True
try:
page = requests.get("https://api.urbandictionary.com/v0/define", params = { "term" : term })
except:
sys.exit("Error getting data")
if page.status_code != 200:
sys.exit("Error getting data")
# ud_items is the list definitions/examples
ud_items = page.json()["list"]
num_items = len(ud_items)
if show_term: print('[' + term + "]\n")
for num, item in enumerate(ud_items, start = 1):
if n > -1 and num > n: break
print(
"[Definition {0}]:\n"
'\n'
"{1}\n"
'\n'
"[Example {0}]:\n"
'\n'
"{2}{3}"
.format(num, item["definition"].strip(), item["example"].strip(),
'\n' if num < num_items else ''))
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment