python - 将 NLTK 分词器与 utf8 结合使用

标签 python csv nltk

我是 Python 的一个相当新的用户,我主要处理导入的文本文件,尤其是 csv 文件,这让我处理起来很头疼。我尝试阅读这样的文档:https://docs.python.org/2/howto/unicode.html但我完全不明白所说的内容。我只是想要一些直接实际的解释。

例如,我想将从互联网导出的大量逐字记录标记为 csv 文件。我想使用 NLTK 的分词器来执行此操作。

这是我的代码:

with open('verbatim.csv', 'r') as csvfile:
    reader = unicode_csv_reader(csvfile, dialect=csv.excel)
    for data in reader:
        tokens = nltk.word_tokenize(data)

当我对数据执行 print() 时,我会得到干净的文本。

但是当我使用 tokenizer 方法时,它返回以下错误:

'ascii' codec can't decode byte 0xe9 in position 31: ordinal not in range(128)

看起来像是编码问题。我对文本所做的每一个小操作总是遇到同样的问题。你能帮我解决这个问题吗?

最佳答案

这应该可以做到:

with open('verbatim.csv') as csvfile:  # No need to set mode to 'r', r is default
    reader = unicode_csv_reader(csvfile, dialect=csv.excel)
    for data in reader:
        tokens = nltk.word_tokenize(unicode(data, 'utf-8'))

否则你也可以尝试:

import codecs
with codecs.open('verbatim.csv', encoding='utf-8') as csvfile:
        reader = unicode_csv_reader(csvfile, dialect=csv.excel)
        for data in reader:
            tokens = nltk.word_tokenize(data)

关于python - 将 NLTK 分词器与 utf8 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36360111/

相关文章:

python - 只能在安装目录中导入 python 模块

python - 扭曲的 UDP 服务器 - 守护进程?

sql-server - 使用docker在Mac os上的sql server中导入csv会出现权限错误

php - 生成 CSV 时更改值

python - 使用 get 与 get() 在 NLTK 中对 FreqDist 进行排序

python - Nltk 的 wordnet lemmatizer 未对所有单词进行词形还原

python - 与NLTK库相关的一段Python代码在不同计算机上的不同结果

python - 使用 win32print + cx_Freeze 时,打印指令不起作用且不会产生任何错误

python - pyhive、sqlalchemy 无法连接到 hadoop 沙箱

javascript - 在html页面中显示csv文件的内容