BeautifulSoup ascii 错误和 csv

BeautifulSoup ascii error and csv

我已经阅读了所有关于该错误的帖子,但仍然无法弄清楚如何调试我的具体问题。

我正在从命令行读取一个 csv 文件。

adamg:NLP adamg$ python3 train_classifier.py samples.csv /Users/adamg/PycharmProjects/NLP/samples

如果我将其作为字节文件打开,如下所示:

training_pages_list_file = sys.argv[1]
with open(training_pages_list_file,'rb') as f:
    reader = csv.reader(f)
    training_page_list.extend(reader)

我收到错误:

  File "train_classifier.py", line 17, in <module>
    training_page_list.extend(reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

但是,如果我将其更改为以文本文件形式读取,或者不进行编码,则在将字符串传递给 BeautifulSoup 对象时出现错误:

training_pages_list_file = sys.argv[1]
html_page_dir = sys.argv[2]
with open(training_pages_list_file,'r') as f:
    reader = csv.reader(f)
    training_page_list.extend(reader)

for page,category in training_page_list:
    cp = CraigsPage(os.path.join(html_page_dir,page))

CraigsPage.py

class CraigsPage():
    def __init__(self, page_file):
        self.doc_name = page_file
        self.soup = BeautifulSoup(open(page_file).read())
        self.title = self.soup.title.string

我收到错误:

  File "train_classifier.py", line 22, in <module>
    cp = CraigsPage(os.path.join(html_page_dir,page))
  File "/Users/adamg/PycharmProjects/NLP-HW1/craiger.py", line 15, in __init__
    self.page = open(page_file).read()
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 6646: ordinal not in range(128)

我该如何解决这个问题?

在Python 3 中,csv 需要文本,所以不要给它字节(以'rb' 打开的文件)。如果文件不是 ascii 文本,则必须对其进行解码:

with open(training_pages_list_file, encoding='iso-8859-1') as f:

或该 CSV 文件中使用的任何其他您知道的编码名称。

If python 2, import codecs 并且类似地使用 codecs.open 而不是内置的 open (在py2中无法处理 encoding/decoding).或者等效地,import io 并使用 io.open.

另一个类似open -- 你需要通知它每个页面文件的编码。

如果您不知道哪个文件使用哪种编码,那么您就有麻烦了,因为您能做的最好的事情就是猜测;一个不错的猜测是 https://pypi.python.org/pypi/chardet ,但是,它 仍然只是一个猜测。

很像,比如说,一个没有关于其记录应该如何布局的信息的二进制数据文件,一个没有关于编码信息的编码文本文件是一个真正糟糕的想法,而且你'我需要一些 detective/archeological/forensic 的工作,还有相当多的运气。