我想知道为什么开发人员使用句子[:]而不是句子。它似乎没有任何区别。
对于输入,代码段和短语将类似于:
snippet = "Have a %%%%"
phrase = "What a %%%"
以下是我正在查看的代码。
for sentence in snippet, phrase:
result = sentence[:]
for word in class_names:
result = result.replace("%%%", word, 1)
删节版本是有两个变量,片段和短语,它们是字符串,可能有%%%,并且将被之前在程序中定义的单词替换为变量&# 34;字"
有谁知道这个人为什么会使用[:]
附带问题,确实
for i in j, k
只是从j迭代到k?
那里的背景迷们的完整背景。它来自于学习Python的艰难之路。我的意见也包括在内。
import random
from urllib import urlopen
import sys
#URL used to populate words
WORD_URL = "http://learncodethehardway.org/words.txt"
#A list of words
WORDS = []
#A dict of phrases structured "Code" : "English explanation of code"
#Each phrase has %%% @@@ or *** which are not explained in this section
#Because these placeholders are not unique and are not variables, the english and code must match
#In a way where the variables for both are in the exact same order.
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
#if the user inputs "english" into the command line as an argument (and nothing else) set Phrase First to True, otherwise its false
#This should allow the user to choose whether the drill in code first or english by typing or not typing English into the command line
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
else:
PHRASE_FIRST = False
# load up the words from the website
#urlopen returns a file that should represent what is on the website Word_Url
#specifically, the website linked in this program is a text file that just has one word per line
#the file like object created by urlopen supports standard file i/o commands from python
#readlines reads every line within the file like object that represents the website
#this uses a for loop to iterate through each of the words from the website provided and append them to the WORDS list
#while using the strip() method to remove all whitespace, in this case, the /n that separates each word
#You will end up with a clean list of words named WORDS
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
#defines function convert that takes input snippet, phrase and has class_names, other_names, results, params, and two loops
def convert(snippet, phrase):
#runs the capitalize function on a random word from WORDS,
#specifically the sample method from random is called with WORDS and snippet.count("%%%") args
#this will use the list of WORDS as the population to pull a random word from
#it will also count the number of %%%'s in the snippet
#and use that as the argument for the amount of words random.sample() will retrieve
#The for loop should then loop through each word that was retrieved and capitalize it
#these capitalized words are then stored in class_names for later use
#This is a local variable so it will reset every time convert is called
class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
#this does the same as above except it does not capitalize and it searches for the number of ***'s instead
other_names = random.sample(WORDS, snippet.count("***"))
#sets two empty lists
results = []
param_names = []
#loops for an amount of times equal to the number of @@@ symbols in the snippet
for i in range(0, snippet.count("@@@")):
#sets new var param_count = to a number beween 1-3
param_count = random.randint(1,3)
#It retrieves words from WORDS the same way that class_names and other_names do, however
#It uses param_count's random int value instead of counting anything from a snippet
#it then joins each word with ', ' and appends it to the empty param_names list
param_names.append(', '.join(random.sample(WORDS, param_count)))
#by now we should have random words prepared for any %%%, ***, and @@@ symbols in the list
#and we should have between 1 and 3 random words stored in list param_names
#now we create a loop that should iterate through a dictionary key pair of snippet and phrase
#sentence will first return snippet, then phrase?
for sentence in snippet, phrase:
#I honestly don't understand this at all
#it will change more when I understand what is being input
print sentence
result = sentence[:]
print result
#This loop iterates through class_names and replaces %%% in result with the current word from classnames
#.replace method targets %%% and replaces it with the current word in class_names, and it limits this replacement to one at a time
#it will set result == to a new version of itself, where the next %%% will get replaced the current word in class_names
for word in class_names:
result = result.replace("%%%", word, 1)
#same as above with ***
for word in other_names:
result = result.replace("***", word, 1)
#same as above with @@@
for word in param_names:
result = result.replace("@@@", word, 1)
#appends the empty results list as defined in the beginning of the function with result
#then it returns reults
results.append(result)
return results
# keep going until they hit CTRL-D
#try Except loopt that only stops at EOFerror which is ctrl D? Otherwise...
try:
while True:
#new variable snippets is equal to a list of all of the keys (code) in PHRASES
snippets = PHRASES.keys()
#it shuffles the snippets
random.shuffle(snippets)
#it iterates through the snippets one at a time
for snippet in snippets:
#new var phrase uses the snippet as the key to set itself (phrase) to that keys value
#at this point, snippet == one Code phrase and phrase equals the resulting English phrase
phrase = PHRASES[snippet]
#new vars question, answer equal to snippet and phrase being run through convert
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"
ooptest.py
Open with
Displaying ooptest.py.
答案 0 :(得分:0)
如果我们清理所有周围的噪音"我们留下了以下内容:
snippet = "Have a %%%%"
phrase = "What a %%%"
for sentence in snippet, phrase:
result = sentence[:]
由于snippet
和phrase
都是字符串,因此它们是不可变的,因此下面的所有计算都可以直接在sentence
上完成,而无需"制作副本&#34 ;
你并不理解这段代码只是因为它做了一些毫无意义的事情......