使用n标记unicode

2024-05-26 14:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有使用utf-8编码的文本文件,其中包含诸如“ore”、“ü”等字符。我想解析这些文件中的文本,但无法使标记器正常工作。如果我使用标准的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']

朋克标记器似乎做得更好:

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']

在第一个标记之前仍然有'\ufeff',我无法确定(不是说我无法删除它)。我做错什么了?非常感谢您的帮助。


Tags: text标记txtclosereaditemsopenutf8
3条回答

UFEE代码是一个“零宽度不间断空格”字符,这不被re模块视为空格,因此使用带unicode和dotall标志的regex r'\w+|[^\w\s]+'PunktWordTokenizer()将此字符识别为一个单词。如果不想手动删除字符,可以使用以下标记器:

nltk.RegexpTokenizer(u'\w+|[^\w\s\ufeff]+')

您应该确保将unicode字符串传递给nltk标记器。我得到了字符串的以下相同的标记化,在我的一端有两个标记化器:

import nltk
nltk.wordpunct_tokenize('müsli pöök rääk'.decode('utf8'))
# output : [u'm\xfcsli', u'p\xf6\xf6k', u'r\xe4\xe4k']

nltk.word_tokenize('müsli pöök rääk'.decode('utf8'))
# output: [u'm\xfcsli', u'p\xf6\xf6k', u'r\xe4\xe4k']

很可能\uFEFF字符是从文件读取的内容的一部分。我怀疑是代币商插入的。^文件开头的{}是不推荐使用的Byte Order Mark形式。如果它出现在其他任何地方,则将其视为zero width non-break space

文件是由微软记事本写的吗?来自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.

尝试使用^{}读取文件。注意使用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'
>>> 

相关问题 更多 >

    热门问题