#改变链表中嵌套链表内的一个项目,全部都改变。引用同一个链表。
>>>empty=[]
>>>nested=[empty,empty,empty]
>>>nested
[[],[],[]]
>>>nested[1].append('python')
>>>nested
[['python'],['python'],['python']]
#分配新值给链表中的某个元素时,不会传送给其他元素。**
>>>netste=[[]]*3
>>>nested[1].append('python')
>>>nested[1]=['Monty'] #id值改变
>>>nesten
[['python'],['Monty'],['python']]
一开始用含有3个引用的链表,每个引用只想一个空链表对象。然后,通过给它追加’python‘来修改这个对象,结果生成了3个指向同一个链表对象['python']的链表。使用新对象['Monty']的引用来覆盖3个对象中的一个。最后一步修改嵌套链表内的3个引用对象中的1个。然而,['python']对象并没有改变,仍然是在嵌套链表中的两处位置被引用。关键是要明白通过对象引用来修改对象与通过覆盖对象引用之间的区别。
2.序列
for item in set(s).defference(t) #遍历在集合s中却不在集合t中的元素
for item in random.shuffle(s) #按随机顺序遍历s中的元素
元组
>>>words=['I','turned','off','the','spectrotoute']
>>>words[2],words[3],words[4]=words[3],words[4],words[2]
>>>words
['I','turned','the','spectroroute','off']
import re4.参数传递
def get_text(file):
text=open(file).read()
text=re.sub('\s+',' ',text)
text=re.sub(r'<.*>?',' ',text)
return text
def set_up(word,properties):
word='locat'
properties.append('noun')
properties=5
>>>w=' '
>>>p=[]
>>>set_up(w,p)
>>>w
' '
>>>p
['noun']
#w的值改变,p的值不变。w的值被分配到一个新的变量word,在函数内部word值被修改。然而,这种变化并没有传递给w。
这个参数传递过程与下面的赋值类似:
w=' '
word=w
word='locat'
w
' '
sent=['take','care','of ','the','sense']
def extract_property(prop):
return [prop(word) for word in sent]
extract_property(len)
def last_letter(word):
return word[-1]
extract_property(last_letter) #函数作为参数时,省略括号。
等价于 extract_property(lambda w :w[-1])
import pdb
import mymoudle
pdb.run('mymoudle.myfunction()')
7.WordNet上位词层次。计数以给定同义词集s为根的上位词层次的大小。找到s的每个下位词的大小,然后将它们加到一起。
一:递归调用
def size1(s):
return 1+sum(size1(child) for child in s.hyponyms())
二:迭代
def size2(s):
layer=[s]
total=0
while layer:
total+=len(layer)
layer=[ h for c in layer for h in c.hyponyms()]
return total
def inset(trie,key,value):
if key:
first,rest=key[0],key[1:]
if first not in trie:
trie[first]={}
inset (trie[first],rest,value)
else:
trie['value']=value
>>>trie=nltk.defaultdict(dict)
>>>insert(trie,'chat','cat')
def raw(file):
contents=open(file).read()
contents=re.sub(r'<.*?>',' ',contents)
contents=re.sub('\s+',' ',contents)
return contents
def snippet(doc,term):
text=' '*30+raw(doc)+' '*30
pos=text.index(term)
return text[pos-30:pos+30]
print "Buding Index..."
files=nltk.corpus.movie_reviews.abspaths()
idx=nltk.Index((w,f) for f in files for w in raw(f).split())
query=' '
while query!="quit":
query=raw_input("query> ")
if queryin idx:
for dc in idx[query]:
print snippet(doc,query)
else:
print "Not found"