我正在尝试从Zed Shaw的“艰苦学习Python”中解决Ex 41。我已经为其创建了文件。该练习从作者的网站检索文本文件。当我在命令行(Ubuntu)上运行它时,它只是把我踢回到没有可见输出的提示。
我不确定如何确定问题所在。我尝试过:
仔细检查代码。据我所知,代码看起来与本书完全相同。
改为在IDLE中运行它,不产生任何输出,仅返回到提示符
使用-v运行python(不产生任何结果)
将URL更改为https和
验证单词列表在该URL(它是)上可用。
我进行的其他任何Python练习仍然运行良好。有没有办法查看更多输出(例如日志文件或强制更多输出的方法),在这里我可以尝试弄清楚发生了什么?
import random
from urllib 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 _init_ that takes self and *** parameters.",
"class %%(object):\n\tdef ***(self, @@@)":
"class %%% has-a function named *** that takes self and @@@ parameters.",
"*** = @@@()":
"Set *** to an instance of class %%%.",
"***.***(@@@)":
"From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
#do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
#load up words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
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 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(results)
return results
# keep going until they hit ctrl-D
try:
while True:
snippets = 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
raw_input("> ")
print "ANSWER: %s\n\n" % answer
except EOFError:
print "\nBye"
答案 0 :(得分:0)
正如jasonharper所提到的,您的照片在convert
内部被调用,而根本没有被调用。
如果您正在寻找一种更通用的调试方法来调试未发生的事情(假设您有一些非常大且复杂的脚本),那么我建议您执行以下操作:
print "start"
放在脚本的开头,print "end"
放在似乎无法处理的指令之前print "end"
:一次将其移出条件块或循环,或移至函数定义的第一行,或从函数定义移至调用的位置。在某些时候,您可能会看到“ end”输出出现(在这种情况下,请检查块的条件或在函数内返回语句,否则可能会阻止您到达print "end"
的位置先前);或者像您的示例一样,您会注意到该调用根本不在您的程序中print "start"
代替print "end"
或在struct Vec3 {
int x;
int y;
int z;
};
template <typename T>
class myProperty {
public:
myProperty(const T& initValue) : m_value{initValue} {}
private:
T m_value;
};
之外移动是很有用的-但想法是相同的:将它们彼此靠近并寻找“显示开始”的时刻,不是终点”情况改变