Python 单词迭代器返回字符
我已尝试为文本中的单词构建我的第一个迭代器:Python 单词迭代器返回字符,python,iterator,Python,Iterator,我已尝试为文本中的单词构建我的第一个迭代器: 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 如
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(),它将逐个字符返回文本
知道我做错了什么吗?是
text
字符串列表吗?如果是字符串(即使包含新行),它会解释结果…我认为您是在将字符串传递给文本,因为这是它生成所有字符的唯一方法。因此,鉴于此,我更新了代码以容纳一个字符串(我所做的只是删除一个循环):
进口稀土
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")))
什么是
文本
?一根绳子?然后,当您对文本中的行进行迭代时,它是对单个字符进行迭代的……您是否试图在空格上拆分?为什么不直接使用text.split()
?如果我在字符串末尾加一个“\n”,我的代码会工作吗?