Python 3.x Python3 split()带生成器

Python 3.x Python3 split()带生成器,python-3.x,Python 3.x,在Python3中,许多方法返回迭代器或生成器对象(而不是python2中的列表或其他重对象) 然而,我发现拆分字符串仍然返回list,而不是generator或iteator: ~$ python3 Python 3.2.2 (...) >>> type('a b c d'.split()) <class 'list'> ~$python3 Python 3.2.2 (...) >>>类型('a b c d'.split()) 是否有使用生成器或迭代器拆分字符

在Python3中,许多方法返回迭代器或生成器对象(而不是python2中的列表或其他重对象)

然而,我发现拆分字符串仍然返回
list
,而不是
generator
iteator

~$ python3
Python 3.2.2
(...)
>>> type('a b c d'.split())
<class 'list'>
~$python3
Python 3.2.2
(...)
>>>类型('a b c d'.split())
是否有使用
生成器
迭代器
拆分字符串的内置程序


(我知道我们可以自己拆分它并编写漂亮的生成器函数。我很好奇标准库或语言中是否有这样的功能)

请从re模块中查看
re.finditer

简言之:

“”“ 返回一个迭代器,该迭代器为字符串中的RE模式在所有非重叠匹配上生成匹配对象。从左到右扫描字符串,并按找到的顺序返回匹配项。空匹配项包括在结果中,除非它们触及另一个匹配项的开头。 “”“

我想它会满足你的需要。例如:

import re
text = "This is some nice text"
iter_matches = re.finditer(r'\w+', text)
for match in iter_matches:
    print(match.group(0))

基于正则表达式的答案很小,但对于那些还是新手的人来说, 想写一个,这里有一个方法:

import string

def gsplit(s,sep=string.whitespace):
    word = []

    for c in s:
        if c in sep:
            if word:
                yield "".join(word)
                word = []
        else:
            word.append(c)

    if word:
        yield "".join(word)
       

text = "This is some nice text"

print(type(gsplit(text)))

for i in (gsplit(text)):
    print(i)

这
是
一些
美好的
文本
[程序完成]

Nice您从文档中指出,这正是我所需要的。@JBernardo我已经看到了这一点-在评论之前,请先在您的帖子下面签出评论。谢谢:)
<class 'generator'>
This
is
some
nice
text

[Program finished]