以下代码有什么问题?

我从《编程集体智慧》书中第118页的“文档过滤”章节复制了以下代码。这段函数通过将文本在任何非字母字符处分割,将文本分解成单词。这样只留下实际的单词,并全部转换为小写。

import re
import math
def getwords(doc):
    splitter=re.compile('\\W*')
    words=[s.lower() for s in splitter.split(doc)
           if len(s)>2 and len(s)<20]
    return dict([(w,1) for w in words])

我实现了这个函数后,遇到了以下错误:

>>> import docclas
>>> t=docclass.getwords(s)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    t=docclass.getwords(s)
  File "docclass.py", line 6, in getwords
    words=[s.lower() for s in splitter.split(doc)
NameError: global name 'splitter' is not defined

回答:

在这里它可以正常工作

>>> import re
>>> 
>>> def getwords(doc):
...     splitter=re.compile('\\W*')
...     words=[s.lower() for s in splitter.split(doc)
...            if len(s)>2 and len(s)<20]
...     return dict([(w,1) for w in words])
... 
>>> getwords ("He's fallen in the water!");
{'water': 1, 'the': 1, 'fallen': 1}

我猜你在代码中打错了字,但在粘贴到这里时改正了。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注