2017-04-09 53 views
0

我試圖建立我的話第一個迭代器文本:迭代器的話返回字符

def words(text): 
regex = re.compile(r"""(\w(?:[\w']*\w)?|\S)""", re.VERBOSE) 
for line in text: 
     words = regex.findall(line) 
     if words: 
       for word in words: 
         yield word 

如果我只用這條線words = regex.findall(line)我檢索列表的所有的話,但如果我使用的功能並做一個NEXT()它將會逐個返回文本字符。

任何想法我做錯了什麼?

+2

什麼是'text'?一個字符串?然後,當你迭代'for line in text'時,它將迭代單個字符... –

+1

你想分割空白嗎?爲什麼不使用'text.split()'? –

回答

1

我相信你正在向文本傳遞一個字符串,因爲這是導致所有字符的唯一方式。因此,鑑於這種情況,我更新的代碼,以適應一個字符串(我所做的只是去掉環中的一個): 進口重新

import re 

def words(text): 
    regex = re.compile(r"""(\w(?:[\w']*\w)?|\S)""", re.VERBOSE) 
    words = regex.findall(text) 
    for word in words: 
     yield word 

print(list(words("I like to test strings"))) 
+0

如果我在我的字符串末尾加上「\ n」,我的代碼是否可以工作? – Kev

-1

text的字符串列表?如果它在字符串上(即使包含新行),它將解釋結果...