【问题标题】:Reading french text files into items in a list - Python将法语文本文件读入列表中的项目 - Python
【发布时间】:2018-04-14 11:46:22
【问题描述】:

我想阅读一堆法语文本文档,并将每个文本文档的内容存储为列表中的一个项目,以便稍后计算 td-idf 分数(通过计算单词等)。

这就是我开始我的代码的方式,它的重点是将每个文档的全文作为一个字符串单独读取:

import os, re
import glob
import operator

file_names = glob.glob(os.path.join("/Corpus", u'*'))
documents=["" for x in file_names]
files=["" for x in file_names]
for infile in (glob.glob(os.path.join("/Corpus", u'*'))):
    file = (open(infile,"r",encoding="utf-8"))
    data = file.read()
    print (data)

当我执行此操作时,他能够打印一些文本,但随后出现以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte

我显然是用 utf-8 编码打开文件,我不明白我在做什么错。

另外,如果我有任何关于如何将包含文档中所有文本的变量data 存储在列表项中的建议,我将不胜感激。以下解决方案无效:

documents.append(data)

谢谢

【问题讨论】:

    标签: python text unicode utf-8 encode


    【解决方案1】:

    您尝试读取的文件似乎未以 UTF-8 编码。最好是尝试找出用于保存文件的编码。如果这不可能,最好的办法是尝试几种编码,看看哪一种有效(参见https://docs.python.org/3/library/codecs.html#standard-encodings)。

    对于您的第二个问题:documents.append(data) 应该可以工作。您的错误是您没有预先初始化 Python 列表。所以这就是你所需要的:

    documents = []
    for infile in file_names:
        ...
        documents.append(data)
    

    最后提示:您正在打开文件,但没有关闭它们。 with 运营商可以在这里为您提供帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-18
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2015-12-13
      • 1970-01-01
      相关资源
      最近更新 更多