这是我根据书上打的,检查了好多遍没发现错误,求指教。万分感谢,加粗部分为错误。
第 28行 def convert(snippet, phrase):
^
SyntaxError: invalid syntax
import random
from urllib.request import urlopen
import sys
WORD_URL="http://learncodethehardway.org/words.txt"
WORDS=[]
PHRASES={
"class %%%(%%%):":
"Make a class named %%% that i _a %%%.",
"class %%%(object):\n\t def __init__(self,***)":
"class %%% has-a __init__ that takes self and *** params.",
"class %%%(object):\n\t def *** (self,@@@)":
"calss %%% has-a function *** that takes self and @@@ params.",
"*** =%%%()":
"Set *** to an instance of class %%%.",
"***.***='***'":
"From *** get the *** atrribute 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
#file=open(r'C:\Users\Basic ResearchCenter\Desktop\words.txt',encoding='utf-8')
#for word in file.readlines():
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[:]
for word in class_names:
result=result.replace("%%%",word,1)
for word in other_names:
result=result.replace("***",word,1)
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")
WORDS.append(str(word.strip(),encoding='utf-8')
这行最后少了个)右括号
WORDS.append(str(word.strip(),encoding='utf-8'))
一般如果某一行报语法错误,可能是这一行或者前一行出问题了,检查的时候重点检查此行和上一行
27行右边少了个括号
第27行少了右括号
WORDS.append(str(word.strip(),encoding='utf-8'))