python - 使用 nltk 标记 unicode

标签 python unicode nltk tokenize

我有使用 utf-8 编码的文本文件,其中包含“ö”、“ü”等字符。我想解析这些文件中的文本,但无法让标记器正常工作。如果我使用标准的 nltk 标记器:

f = open('C:\Python26\text.txt', 'r') # text = 'müsli pöök rääk'
text = f.read()
f.close
items = text.decode('utf8')
a = nltk.word_tokenize(items)

输出:[u'\ufeff', u'm', u'\xfc', u'sli', u'p', u'\xf6', u'\xf6', u' k', u'r', u'\xe4', u'\xe4', u'k']

Punkt 分词器似乎做得更好:

f = open('C:\Python26\text.txt', 'r') # text = 'müsli pöök rääk'
text = f.read()
f.close
items = text.decode('utf8')
a = PunktWordTokenizer().tokenize(items)

输出:[u'\ufeffm\xfcsli', u'p\xf6\xf6k', u'r\xe4\xe4k']

在我无法弄清楚的第一个 token 之前仍然有'\ufeff'(不是我无法删除它)。我究竟做错了什么?非常感谢您的帮助。

最佳答案

\uFEFF 字符更有可能是从文件中读取的内容的一部分。我怀疑它是由标记器插入的。文件开头的 \uFEFFByte Order Mark 的弃用形式.如果它出现在其他任何地方,则将其视为 zero width non-break space .

文件是由 Microsoft 记事本编写的吗?来自 the codecs module docs :

To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls "utf-8-sig") for its Notepad program: Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is written.

尝试使用 codecs.open() 读取您的文件反而。注意使用 BOM 的 "utf-8-sig" 编码。

import codecs
f = codecs.open('C:\Python26\text.txt', 'r', 'utf-8-sig')
text = f.read()
a = nltk.word_tokenize(text)

实验:

>>> open("x.txt", "r").read().decode("utf-8")
u'\ufeffm\xfcsli'
>>> import codecs
>>> codecs.open("x.txt", "r", "utf-8-sig").read()
u'm\xfcsli'
>>> 

关于python - 使用 nltk 标记 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228202/

相关文章:

python - 将一组文本文件中的第 2 列添加到 1 个文本文件中

unicode - 我如何使用 io.open 在 lua 中打开 unicode 路径

python - 使用 nltk 实现 idf

python - nltk StanfordNERTagger : NoClassDefFoundError: org/slf4j/LoggerFactory (In Windows)

python - 如何比较两个列表?

python - 字符串切片的不可编写脚本的 Int 错误

python - 在 Python 中创建一个从 STDIO 读取并循环写入 STDOUT 的服务

c# - 如何从字符串中删除 unicode.OtherSymbol

android - Android 的 Unicode 支持

python - NLTK 句子边界错误