如何解决TypeError:使用NLTK word_tokenize时预期的字符串或类似字节的对象
我正在尝试导入CSV文件,然后使用NLTK分析文本。 CSV文件包含几列,但现在我只想分析此文件中的一列。
csv文件的示例为: sample data from csv file
读取CSV文件和使用word_tokenize的代码如下:
import pandas as pd
import nltk
#nltk.download('all')
data=pd.read_csv("Output-analysis.csv")
print (data.SAT_COMMENTS)
from nltk.tokenize import word_tokenize
tokenize_word=word_tokenize(data.SAT_COMMENTS)
print(tokenize_word)
看来我可以读取并打印SAT_Comment列没问题,但是当我尝试使用word_tokenize时,它指向的是csv文件中的某些行,然后是TypeError:预期的字符串或类似字节的对象错误。
错误详细信息:
Traceback (most recent call last):
File "C:\Users\Rachel\Desktop\SAT analysis\Attempts.py",line 22,in <module>
tokenize_word=word_tokenize(data.SAT_COMMENTS)
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\__init__.py",line 129,in word_tokenize
sentences = [text] if preserve_line else sent_tokenize(text,language)
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\__init__.py",line 107,in sent_tokenize
return tokenizer.tokenize(text)
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",line 1272,in tokenize
return list(self.sentences_from_text(text,realign_boundaries))
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",line 1326,in sentences_from_text
return [text[s:e] for s,e in self.span_tokenize(text,realign_boundaries)]
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",in <listcomp>
return [text[s:e] for s,line 1316,in span_tokenize
for sl in slices:
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",line 1357,in _realign_boundaries
for sl1,sl2 in _pair_iter(slices):
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",line 314,in _pair_iter
prev = next(it)
File "C:\Users\Rachel\AppData\Local\Programs\Python\Python38\lib\site-packages\nltk\tokenize\punkt.py",line 1330,in _slices_from_text
for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
有什么建议吗?我知道word_tokenize处理一次不是针对字符串,但我无法弄清楚这里出了什么问题。谢谢
解决方法
确保该列中没有NaN
data.SAT_COMMENTS = data.SAT_COMMENTS.fillna('')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。