2015-01-21 100 views
0

我是一個新手,我寫了一個tokenize函數,它基本上接受一個由句子組成的txt文件,並根據空格和標點拆分它們。這裏的東西是它給了我一個父列表中的子列表的輸出。分割python列表

我的代碼:

def tokenize(document) 
    file = open("document.txt") 
    text = file.read() 
    hey = text.lower() 
    words = re.split(r'\s\s+', hey) 
    print [re.findall(r'\w+', b) for b in words] 

我的輸出:

[['what', 's', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'eggs', 'warden'], ['his', 'dad', 'was', 'warden', 'in', 'the', 'kitchen', 'poaching', 'eggs']] 

所需的輸出:

['what', 's', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'eggs', 'warden']['his', 'dad', 'was', 'warden', 'in', 'the', 'kitchen', 'poaching', 'eggs'] 

如何刪除父列表中的出我的輸出?我需要在代碼中進行哪些更改才能刪除外部列表括號?

+1

爲什麼要取出外支架?你有一個列表子列表。 – 2015-01-21 06:51:39

+0

我不希望子列表實際出現在我的輸出中。 – Wolf 2015-01-21 06:53:06

+0

然後你會得到一個元組(用'()')。你是否試圖以特定的方式打印出來? – 2015-01-21 06:53:35

回答

0

這應該工作

print ','.join([re.findall(r'\w+', b) for b in words]) 
+0

不,它不按預期方式工作:/ – Wolf 2015-01-21 06:57:21

2

我希望他們作爲個人名單

Python中的函數只能返回一個值。如果你想返回兩個東西(例如,對於你的情況,有兩個單詞列表),你必須返回一個對象,它可以包含兩個東西,像列表,元組,字典。

不要混淆你想怎麼打印輸出對什麼是對象返回

要簡單地打印清單:

for b in words: 
    print(re.findall(r'\w+', b)) 

如果你這樣做,那麼你的方法不返回任何東西(它實際上返回None)。

要返回兩個名單:

return [re.findall(r'\w+', b) for b in words] 

然後打電話給你的方法是這樣的:

word_lists = tokenize(document) 
for word_list in word_lists: 
    print(word_list) 
0

我有一個例子,我的猜測是不是從你的問題太大的不同..

其中我只佔用列表的某個部分。

>>> a = [['sa', 'bbb', 'ccc'], ['dad', 'des', 'kkk']] 
>>> 
>>> print a[0], a[1] 
['sa', 'bbb', 'ccc'] ['dad', 'des', 'kkk'] 
>>>