首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python帮助-以困难的方式学习Python练习41 "phrase = PHRASES[snippet]“

Python帮助-以困难的方式学习Python练习41 "phrase = PHRASES[snippet]“
EN

Stack Overflow用户
提问于 2013-08-26 14:38:26
回答 1查看 1.8K关注 0票数 2

我正在学习python --这是我正在学习的第一门编程语言。我对其中的一行代码感到有点困惑。完整的代码也可以在http://learnpythonthehardway.org/book/ex41.html上找到

代码语言:javascript
复制
import random
from urllib 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 *** 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 the 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 name
    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 = PHRASES.keys()
    # returns a randomly shuffled dictionary keys list
    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"

这是我不太理解的第11行代码:phrase = PHRASES[snippet]。既然for snippet in snippets:中的代码段循环遍历随机混洗短语列表的关键字,为什么代码不能简单地为phrase = snippet。提前感谢您的帮助。干杯-达伦

EN

回答 1

Stack Overflow用户

发布于 2020-05-20 11:45:22

获取字典中key"snippet“的值

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18438060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档