【问题标题】:Got stuck while reading files读取文件时卡住了
【发布时间】:2019-09-27 23:35:54
【问题描述】:

代码的作用

我正在尝试从我提供的文件夹中读取每个文件,并使用 python 中的 bs4 Soup 包提取一些行。

我在读取某些 unicode 字符无法读取的文件时出错。

错误

Traceback(最近一次调用最后一次):文件“C:-----\check.py”,第 25 行,在 汤=BeautifulSoup(text.read(), 'html.parser') 文件 "C:\Python\Python37\lib\encodings\cp1252.py", 第 23 行,在解码中 return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 3565:字符映射到

   from bs4 import BeautifulSoup
   from termcolor import colored
   import re, os

   import requests
   path = "./brian-work/"
   freddys_library = os.listdir(path)
def getfiles():
  for r, d, f in os.walk(path):
    for file in f:
        if '.html' in file:
            files.append(os.path.join(r, file))
  return files


for book in getfiles():
    print("file is printed")
    print(book)
    text = open(book, "r")
    soup=BeautifulSoup(text.read(), 'html.parser')
    h1 = soup.select('h1')[0].text.strip()
    print(h1)
    if soup.find('h1'):
      h1 = soup.select('h1')[0].text.strip()
    else:

      print ("no h1")
      continue

    filename1=book.split("/")[-1]
    filename1=filename1.split(".")[0]
    print(h1.split(' ', 1)[0])
    print(filename1) 
    if h1.split(' ', 1)[0].lower() == filename1.split('-',1)[0] :
      print('+++++++++++++++++++++++++++++++++++++++++++++');
      print('same\n');
    else:
      print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
      print('not')
      count=count+1

请帮助我在这里更正什么。

谢谢

【问题讨论】:

标签: python file unicode character-encoding


【解决方案1】:

问题是在不知道其编码的情况下打开文件。根据open 文档,text = open(book, "r") 的默认编码是从locale.getpreferredencoding(False) 返回的值,即您的系统的cp1252。该文件是其他编码,因此失败。

使用text = open(book, "rb")(二进制模式)并让BeautifulSoup 解决。 HTML 文件通常会指明它们的编码。

您也可以使用text = open(book,encoding='utf8') 或任何正确的编码(如果您已经知道)。

【讨论】:

  • 谢谢哥们,open(book,encoding='utf8') 这里不需要模式吗?
  • @Mohammed Read 是默认设置。
猜你喜欢
  • 2010-11-05
  • 2019-07-07
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多