python isinstance(obj, tpyes.GeneratorType) 失败

标签 python generator spacy

如果我检查类型 types.GeneratorType和生成器对象 text[0]每个,都返回 <class 'generator'> 。但是,每当我使用isinstance()时,它返回 False 。我做错了什么?

import types
import spacy

nlp = spacy.load('en')
text = [nlp(' '.join(docs)).sents]

print(types.GeneratorType)

Out[27]: <class 'generator'>


print(text)
Out[28]: [<generator object at 0x000001F4407F8950>]

print(type(text[0]))
Out[29]: <class 'generator'>


print(isinstance(text[0], types.GeneratorType))
Out[30]: False

最佳答案

您的代码读起来有点困惑,因为变量 text 是一个包含生成器对象的列表。但我认为您在这里看到的可以归结为一个相当微妙的区别:the difference between generator functions and generators在Python中。

import types
import inspect

def generator_function():
    for i in range(100):
        yield i

generator = (i for i in range(100))

isinstance(generator_function, types.GeneratorType)  # False
isinstance(generator, types.GeneratorType)  # True

inspect.isgeneratorfunction(generator_function)  # True
inspect.isgeneratorfunction(generator)  # False

spaCy 的 Doc.sents 属性是一个生成器函数,可生成句子跨度 – see here以便实现。

关于python isinstance(obj, tpyes.GeneratorType) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925084/

相关文章:

python - PyCharm 在设置解释器 : no such option: --python 时出错

python - Word Mover 距离与 SpaCy 的非标准化结果

python - 基于规则的 Spacy 实体匹配器

python webkit webview : Why does the history have dates that equal 0. 0,需要修复什么?

python - 为什么 'the' 在 .remove 之后仍然存在?

javascript - 在导航栏中显示未读计数

php - SHA512在PHP中生成随机数

python - 生成器方法 throw 的返回值

list - 出于效率原因,ghc 是否将仅使用一次的列表转换为生成器?

spacy - Spacy 中的多词表达识别