我对python非常新,实际上这是我的WK2试图跟随这本书,学习python hard Way 。。
对于ex41.py中的代码,我有两个问题。
-
我不太明白为什么它具有以下语句:
for i in range(0, snippet.count("@@@")):
由于
snippet.count("@@@")
永远是1,那么我只有1个值,这是0。为什么我们无论如何都循环呢?为什么我们不能直接设置变量param_count
和param_names
? -
我也很混淆:
for word in param_names: result = result.replace("@@@", word, 1)
我知道
param_names
是最多三个单词的单词列表,但是由于@@@
在摘要和短语中仅显示一次,因此如何替换1次以上?
谢谢,
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):ntdef __init__(self, ***)" :
"class %%% has-a __init__ that takes self and *** parameters.",
"class %%%(object):ntdef ***(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 '***'."
}
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
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[:]
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 = 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: %snn" % answer
except EOFError:
print "nBye"
参考您的问题2(result = result.replace("@@@", word, 1)
):
通常,您不会替换一次以上。
使用可选的参数" 1",只有第一个" @@@"被替换。
例如:
str = "Hello @@@ hello @@@."
print str.replace("@@@", "world", 1)
print str.replace("@@@", "world", 2)
Hello world hello @@@.
Hello world hello world.
,但在这种情况下,它是一个循环,并且在每个循环中替换一个项目。
str = "Hello @@@ hello @@@."
Loop1
str = "Hello world hello @@@."
Loop2
str = "Hello world hello world."
最后,如果您想知道为什么@@@被一个单词替换。
看一下联接字符串方法:
param_names.append(', '.join(random.sample(WORDS, param_count)))
此方法基本上要做的是将几个字符串转换为一个字符串。
print ', '.join(["Word1", "Word2"])
Word1, Word2
param_names
包含参数的后续名称,因此,如果您具有['param1', 'param2']
和字符串'(@@@, @@@)'
,则希望第一个替换为result.replace("@@@", 'param1', 1)
,因此它将仅替换@@@
的第一次出现CC_12。然后,您要替换第二个@@@
以具有'(param1, param2)'
。如果没有约束,您最终将使用'(param1, param1)'
,即@@@
的所有出现将被第一个参数的名称替换。所有其他地方持有人(类和"其他")也适用。
对于某些特定输入数据来说似乎有多余的事实并不意味着它通常是多余的。除脚本中的示例以外,其他可能的输入需要其他可能的输入,而没有此算法将是不正确的。