python - 处理文本时遇到字符编码问题

标签 python encoding gensim

我正在尝试处理大型语料库,但在 preprocess_string( ) 中它返回如下所示的错误

Traceback (most recent call last): File "D:/Projects/docs_handler/data_preprocessing.py", line 60, in <module> for temp in batch(iterator,1000): File "D:/Projects/docs_handler/data_preprocessing.py", line 30, in batch for item in iterable: File "D:/Projects/docs_handler/data_preprocessing.py", line 23, in iter_tokenized_documents document = preprocess_string(open(os.path.join(root, file)).read().strip(),filters=CUSTOM_FILTERS) File "C:\Users\koradg\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 16144: character maps to <undefined>
<小时/>
Versions
Windows-10-10.0.17763-SP0
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]
NumPy 1.17.0
SciPy 1.3.0
gensim 3.8.0
FAST_VERSION 0
<小时/>
def iter_tokenized_documents(input_directory):
    """Iterate over all documents, yielding a document (=list of utf8 tokens) at a time."""
    for root, dirs, files in os.walk(input_directory):
        for file in filter(lambda file: file.endswith('.txt'), files):
            document = preprocess_string(open(os.path.join(root, file)).read().strip(),filters=CUSTOM_FILTERS)
            if(len(document)):
                yield document

如何运行而不出错?

最佳答案

从您的问题看来,您遇到了编码错误。 只需在打开文件中使用 encoding='utf-8' 即可。 如果该章程不重要,请在打开文件中使用此errors="ignore"

关于python - 处理文本时遇到字符编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688029/

相关文章:

python - 主题建模一致性得分 :

python - 主循环不等待 python 多处理池完成并卡住

Python 查找时间在列表中不连续

python - 将单个数据帧中的多个列合并到单个数据帧中

python - Django:手动获取一个URL对应的 View

java - 使用不同编码编码的两个不同字符串是否可以具有相同的字节序列?

text-mining - gensim 的 get_document_topics 方法返回的概率不等于 1

php - 一个奇怪的字符编码案例,PHP 到 MySQL 并返回

javascript - 输入意外结束(第 1 行)和未定义函数?

python - 如何从gensim的word2vec中提取词汇向量?