【发布时间】:2020-07-17 08:30:15
【问题描述】:
我正在使用 python 3.7 64 位。 nltk 版本 3.4.5。
当我尝试使用 word_tokenize 将 nltk.book 中的 text6 转换为令牌时,出现错误。
import nltk
from nltk.tokenize import word_tokenize
from nltk.book import *
tokens=word_tokenize(text6)
代码在空闲 3.7 中完成
下面是我执行最后一条语句时的错误。
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
tokens=word_tokenize(text6)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\__init__.py", line 144, in word_tokenize
sentences = [text] if preserve_line else sent_tokenize(text, language)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\__init__.py", line 106, in sent_tokenize
return tokenizer.tokenize(text)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1277, in tokenize
return list(self.sentences_from_text(text, realign_boundaries))
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1331, in sentences_from_text
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1331, in <listcomp>
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1321, in span_tokenize
for sl in slices:
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1362, in _realign_boundaries
for sl1, sl2 in _pair_iter(slices):
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 318, in _pair_iter
prev = next(it)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tokenize\punkt.py", line 1335, in _slices_from_text
for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
请帮忙。提前致谢。
在进行一些故障排除时,我创建了一个示例 nltk.text.Text 对象并尝试使用 nltk.word_tokenize 对其进行标记。我仍然遇到同样的错误。请看下面的截图。
但是在对字符串调用 nltk.word_tokenize() 时,它可以正常工作。
>>> tt="Python is a programming language"
>>> tokens2=nltk.word_tokenize(tt) #Not throwing error
>>> type(tt)
<class 'str'>
>>> type(text6)
<class 'nltk.text.Text'>
>>>
【问题讨论】:
-
您发布的代码未定义 text6。根据异常,不能是字符串。
-
错误消息告诉您
word_tokenize函数需要一个字符串作为其输入。你给它一个 Book 对象。似乎 Book 对象公开了一个包含每个单词的迭代器:' '.join(text6)可能会给您一个字符串 - 但 Book 对象已经有它们的标记化版本,可用作.tokens(或.token,如果这不起作用)。跨度> -
@TerryJanReedy 它来自
from nltk.book import *,它将nltk.book中的所有名称导入当前范围。 -
@MatsLindh,我试过 text6.tokens()。它给了我一个错误说明 TypeError: 'list' object is not callable。我是一名 c# 开发人员,对 python 完全陌生。我只是对nltk进行一些分析,以学习自然语言处理和python。你能帮我解决这个错误吗?
-
@MatsLindh,我添加了一些屏幕截图,可以更清楚地说明问题。请检查。提前致谢。
标签: python nltk python-3.7