Please help me in ex41.py

This is my script:

import random
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%):":
        "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)":
        "class %%% has-a __init__ that makes self and *** params.",
    "class %%%(object):\n\tdef ***(self, @@@)":
        "class %%% has-a function *** that takes self and @@@ params.",
    "*** = %%%()":
        "Set *** to an instance of class %%%.",
    "***.***(@@@)":
        "From *** get the *** function, call it with params self, @@@.",
    "***.*** = '***'":
        "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrases first
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True
else:
    PHRASE_FIRST = False

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(), encoding="utf-8"))


def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(
            random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results


# keep going until they hit CTRL-D
try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input(">")
            print(f"ANSWER:  {answer}\n\n")
except EOFError:
    print("\nBye")

And I am getting the following result while running this ex41.py

PS C:\Users\AMISHA SINGH\Documents\Py> python ex41.py
Traceback (most recent call last):
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 1317, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1244, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1290, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1239, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1026, in _send_output
    self.send(msg)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 966, in send
    self.connect()
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 938, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ex41.py", line 30, in <module>
    for word in urlopen(WORD_URL).readlines():
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 525, in open
    response = self._open(req, data)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 543, in _open
    '_open', req)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 1345, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Users\AMISHA SINGH\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 1319, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

When you post code do this:

[code]
your code here
[/code]

I fixed it up for you. Now, for the error I think you are having problems accessing the domain from this computer. Can you get to it with your web browser? Copy and paste the http://learncodethehardway.org/words.txt url into your browser and see if you access it.

1 Like

Thank You Sir for your help. I will try it.

Great, let me know what happens. The error you’re getting is because your internet provider says my website does not exist.

Wonder if you could point me in the right direction on ex41. I’m able to open the .txt file in Chrome, but python throws connection refused errors.
Thanks

Traceback (most recent call last):
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 1319, in do_open
h.request(req.get_method(), req.selector, req.data, headers,
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 1230, in request
self._send_request(method, url, body, headers, encode_chunked)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 1276, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 1225, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 1004, in _send_output
self.send(msg)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 944, in send
self.connect()
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 1392, in connect
super().connect()
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\http\client.py”, line 915, in connect
self.sock = self._create_connection(
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\socket.py”, line 808, in create_connection
raise err
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\socket.py”, line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “ex41.py”, line 30, in
for word in urlopen(WORD_URL).readlines():
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 222, in urlopen
return opener.open(url, data, timeout)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 525, in open
response = self._open(req, data)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 542, in _open
result = self._call_chain(self.handle_open, protocol, protocol +
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 502, in _call_chain
result = func(*args)
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 1362, in https_open
return self.do_open(http.client.HTTPSConnection, req,
File “C:\Users\lindseycu\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py”, line 1322, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>

import random
from urllib.request import urlopen
import sys

WORD_URL = "https://learncodethehardway.org/words.txt"
WORDS=[]

PHRASES = {
    "class %%%(%%%):":
      "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)" :
      "class %%% has-a __initII that takes self and *** params.",
    "class %%%(object):\n\tdef ***(self, @@@)":
      "class %%% has-a function *** that takes self and @@@ params.",
    "*** = %%%()":
      "Set *** to an instance of class %%%.",
    "***.***(@@@)":
      "From *** get the function, call it with the params self, @@@.",
    "***.*** = '***'":
      "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrases first
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST=True
else:
    PHRASE_FIRST=False

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(),encoding="utf-8"))

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results=[]
    param_names=[]

    for i in range(0,snippet.count("@@@")):
        param_count=random.randint(1,3)
        param_names.append(', '.join(
            random.samples(WORDS, param_count)))

    for sentence in snippet, phrase:
        result=sentence[:]

        #fake class names
        for word in class_names:
            result=result.replace("%%%",word,1)

        #for other names
        for word in other_names:
            result=result.replace("***",word, 1)

        #fake parameter lists
        for word in param_names:
            result=result.replace("@@@",word,1)

        results.append(result)


    return results


# keep going until they hit CTRL+D
try:
    while True:
        snippets= list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input("> ")
            print(f"Answer: {answer}\n\n")
except EOFError:
    print("\nBye")

Actually, never mind. Figured out that it was related to the connection on my side. Thanks.

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.