属性错误:'NoneType'对象没有属性'start'数据营练习



我正在做关于Python中NLP的Datacamp课程。其中一个练习要求以下内容:使用 re.search(( 搜索单词"coconuts"在scene_one中的第一个出现。将结果存储在匹配中。分别使用其 .start(( 和 .end(( 方法打印匹配的开始和结束索引。

我正在这样做:

match = re.search("coconuts", scene_one)
print(match.start(), match.end())
print(match)

它似乎在iPython shell中正常工作,但是当我在Jupyter笔记本上运行代码时,我收到以下错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-dbcdf93b0e90> in <module>
----> 1 print(match.start(), match.end())
AttributeError: 'NoneType' object has no attribute 'start'

什么意思?

在调用任何方法之前,您首先必须检查 match 对象是否存在:

match = re.search("coconuts", scene_one)
if match is not None:
print(match.start(), match.end())
print(match)

相关内容

最新更新