Python 2.7 下面的代码有什么问题?
我从《编程集体智能》第118页“文档过滤”一章中复制了以下代码。此函数通过将文本拆分为非字母的任何字符来将文本拆分为单词。这只剩下实际单词,全部转换成小写Python 2.7 下面的代码有什么问题?,python-2.7,machine-learning,artificial-intelligence,documentfilter,Python 2.7,Machine Learning,Artificial Intelligence,Documentfilter,我从《编程集体智能》第118页“文档过滤”一章中复制了以下代码。此函数通过将文本拆分为非字母的任何字符来将文本拆分为单词。这只剩下实际单词,全部转换成小写 import re import math def getwords(doc): splitter=re.compile('\\W*') words=[s.lower() for s in splitter.split(doc)
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}
我觉得你在代码中输入了一个错误,但当你粘贴到这里时,它是正确的