Skip to content

Commit

Permalink
fix: correct python sample merge issues (#346)
Browse files Browse the repository at this point in the history
* chore: add missing image files

* fix: simplify python code and consistent quotes

* fix: consistent quotes

* fix: use curl for lookup

* fix: correct typo
  • Loading branch information
dwmkerr authored Oct 1, 2024
1 parent a460055 commit c3f6823
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 93 deletions.
48 changes: 25 additions & 23 deletions samples/programs/lookup/lookup-v2.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
import json
import subprocess
import sys
import urllib.request
import urllib.parse
import json

def search_for_word(word):
# Encode the word for HTML.
encoded_word = urllib.parse.quote(word.encode('utf8'))
encoded_word = urllib.parse.quote(word.encode("utf8"))

# Construct the URL required to load the definition.
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
command = ["curl", url]

# Run the 'curl' command to retrieve the definition.
result = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)

# If there was an error, show it as the definition.
if result.returncode != 0:
return "error: " + result.stderr

# Try and download the definition using the amazing dictionaryapi.dev site.
try:
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
response = urllib.request.urlopen(url)
if response.status == 404:
print("NOT FOUND")
sys.exit(1)
with urllib.request.urlopen(url) as response:
raw_json_data = response.read().decode('utf-8')
# If the word is not found, return an empty definition.
except urllib.error.HTTPError as http_error:
if http_error.code == 404:
return ""
raise

# Now try and parse the data.
data = json.loads(raw_json_data)
first_definition = data[0]['meanings'][0]['definitions'][0]['definition']
data = json.loads(result.stdout)

# Return the result.
return first_definition
# Grab the first 'meaning' value. If it doesn't exist in the response then
# the word was not found.
try:
return data[0]["meanings"][0]["definitions"][0]["definition"]
except KeyError:
return "definition not found!"

# Read standard input until there is nothing left to read.
while True:
Expand All @@ -49,4 +51,4 @@ def search_for_word(word):
definition = search_for_word(stripped_word)

# Write the result.
print(word, " - ", definition)
print(word, "-", definition)
58 changes: 25 additions & 33 deletions samples/programs/lookup/lookup-v3.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import sys
import argparse
import urllib.request
import urllib.parse
import json
import os

ERROR_HTTP = 1
ERROR_PARSE = 2
import subprocess
import sys
import urllib.parse

# Create an argument parser and define the arguments for our program.
parser = argparse.ArgumentParser()
Expand All @@ -21,36 +18,31 @@

def search_for_word(word):
# Encode the word for HTML.
encoded_word = urllib.parse.quote(word.encode('utf8'))
encoded_word = urllib.parse.quote(word.encode("utf8"))

# Construct the URL required to load the definition.
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
command = ["curl", url]

# Run the 'curl' command to retrieve the definition.
result = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)

# If there was an error, show it as the definition.
if result.returncode != 0:
return "error: " + result.stderr

# Try and download the definition using the amazing dictionaryapi.dev site.
try:
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
response = urllib.request.urlopen(url)
if response.status == 404:
print("NOT FOUND")
sys.exit(1)
with urllib.request.urlopen(url) as response:
raw_json_data = response.read().decode('utf-8')
# If the word is not found, return an empty definition.
except urllib.error.HTTPError as http_error:
if http_error.code == 404:
return ""
raise
except Exception as e:
sys.stderr.write("An error occurred trying to download the definition of '{}'".format(word))
sys.exit(ERROR_HTTP)

# Now try and parse the data.
data = json.loads(result.stdout)

# Grab the first 'meaning' value. If it doesn't exist in the response then
# the word was not found.
try:
data = json.loads(raw_json_data)
first_definition = data[0]['meanings'][0]['definitions'][0]['definition']
except Exception as e:
sys.stderr.write("An error occurred trying to parse the definition of '{}'".format(word))
sys.exit(ERROR_PARSE)

# Return the result.
return first_definition
return data[0]["meanings"][0]["definitions"][0]["definition"]
except KeyError:
return "definition not found!"

def write_definition(word, definition):
# Check if stdout is a terminal - if it is we'll colour the output.
Expand Down
62 changes: 25 additions & 37 deletions samples/programs/lookup/lookup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env python3

import sys
import argparse
import urllib.request
import urllib.parse
import json
import os
import subprocess
import sys
import urllib.parse

ERROR_INTERRUPT = 1
ERROR_HTTP = 2
Expand Down Expand Up @@ -42,42 +41,31 @@

def search_for_word(word):
# Encode the word for HTML.
encoded_word = urllib.parse.quote(word.encode('utf8'))
encoded_word = urllib.parse.quote(word.encode("utf8"))

# Construct the URL required to load the definition.
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
command = ["curl", url]

# Run the 'curl' command to retrieve the definition.
result = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)

# If there was an error, show it as the definition.
if result.returncode != 0:
return "error: " + result.stderr

# Try and download the definition using the amazing dictionaryapi.dev site.
try:
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{}".format(encoded_word)
response = urllib.request.urlopen(url)
if response.status == 404:
print("NOT FOUND")
sys.exit(1)
with urllib.request.urlopen(url) as response:
raw_json_data = response.read().decode('utf-8')
# If the word is not found, return an empty definition.
except urllib.error.HTTPError as http_error:
if http_error.code == 404:
return ""
raise
# If the user hits ctrl hit, exit without an error message.
except KeyboardInterrupt:
sys.exit(ERROR_INTERRUPT)
except Exception as e:
sys.stderr.write("An error occurred trying to download the definition of '{}'".format(word))
sys.exit(ERROR_HTTP)

# Now try and parse the data.
data = json.loads(result.stdout)

# Grab the first 'meaning' value. If it doesn't exist in the response then
# the word was not found.
try:
data = json.loads(raw_json_data)
first_definition = data[0]['meanings'][0]['definitions'][0]['definition']
# If the user hits ctrl hit, exit without an error message.
except KeyboardInterrupt:
sys.exit(ERROR_INTERRUPT)
except Exception as e:
sys.stderr.write("An error occurred trying to parse the definition of '{}'".format(word))
sys.exit(ERROR_PARSE)

# Return the result.
return first_definition
return data[0]["meanings"][0]["definitions"][0]["definition"]
except KeyError:
return "definition not found!"

def write_definition(word, definition):
# Check if stdout is a terminal - if it is we'll colour the output.
Expand Down

0 comments on commit c3f6823

Please sign in to comment.