LPYTHW练习41:键入所有内容,但不运行

时间:2018-09-24 09:17:58

标签: python python-3.x

我按原样键入了所有内容,但是它什么也没做。控制台只是空白。有人知道出什么问题了吗?
我尝试做所有事情,并遍历了几次代码,看起来应该与给出的代码完全一样...
我不知道为什么它不运行,我会及时解决。

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 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 params self, @@@.",
"***.*** = '***'":
    "From *** get the *** attribute and set it to '***'."}

if len(sys.argv) == 2 and sys.argv[1] == "english":
  PHRASE_FIRST = True
else:
  PHRASE_FIRST = False

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 param name
      for word in param_names:
          result = result.replace('@@@', word, 1)

      results.append(result)

  return results

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")

1 个答案:

答案 0 :(得分:0)

  

我按原样键入了所有内容

不,您没有。如果您将其与e。 G。问题How to read the code of exercise 41 from learn python the hard way?中的代码,您可以看到Aran-Fey注释了什么-while True:循环中的缩进是错误的。