2012-06-21 34 views
-2

我在Python集中插入變量時遇到了問題。有誰知道我得到了什麼:s.insert(len(s),x)在Python中插入變量集

我的問題是當我想要插入 x添加到一個集合或列表。

爲什麼我不能做到這一點?以及如何解決這個問題?

我的代碼:

import nltk 
import Set 

FILE=open("out.txt", "w") 
FILE.writelines("this is to show why using NNs :)!!!!\n") 

text1=raw_input() 
FILE.writelines("first text loaded.....\n") 
sentences1=text1.split('.') 
FILE.writelines("first text splited.....\n") 

text2=raw_input() 
FILE.writelines("second text loaded.....\n") 
sentences2=text2.split('.') 
FILE.writelines("second text splited.....\n") 



s=['a','b'] 
FILE.writelines("\n NNs for first:\n") 
for sen in sentences1: 
    tokens1= nltk.word_tokenize(sen) 
    tagged1 = nltk.pos_tag(tokens1) 
    for (x, y) in tagged1: 
     if y=='NN': 
      FILE.writelines(x+",") 
      s.insert(len(s),x) 
FILE.writelines(len(s1)) 


FILE.writelines("\n NNs for second:\n") 
for sen in sentences2: 
    tokens2= nltk.word_tokenize(sen) 
    tagged2 = nltk.pos_tag(tokens2) 
    for (x, y) in tagged2: 
     if y=='NN': 
      FILE.writelines(x+",") 
      s2[len(s2)]= x 
FILE.writelines(len(s2)) 

print "********temoum**********" 
FILE.close() 

回答

16

s是一個列表,你可以這樣做:

s.insert(len(s),x) 

這意味着:這意味着你」 「在len(s)位置插入元素x到列表s」重新插入列表末尾的元素。

s是一組,你可以這樣做:

s.add(x) 

一組有沒有訂單,讓您不需要指定位置。一套也不包含重複,如果你需要它可以是有用的。如果不是,您可以使用列表來代替。


意外IndentationError可以在這裏找到:

if y=='NN': 
    FILE.writelines(x+",") 
     s.insert(len(s),x) 

這應該是這樣的:

if y=='NN': 
    FILE.writelines(x+",") 
    s.insert(len(s),x) 
+0

+1用來說明設定VS名單。 – Ryan

+0

s.add(x)還有問題 – user1472850

+0

我錯過了什麼,或者是第一個只是說's.append(c)'的複雜方式嗎? – delnan