问题:从字符串中删除长破折号

我正在尝试从网站读取 html 内容到 Python 以分析那里的文本并确定它们属于哪个类别。当我尝试使用它们时,它们进入 NoneType 时,我遇到了长破折号的问题。我已经尝试了这个网站上建议的几个修复,但没有一个奏效。

from bs4 import BeautifulSoup
import re
import urllib.request
response = urllib.request.urlopen('website-im-opening')
content = response.read().decode('utf-8')
#this does not work
content = content.translate({0x2014: None})
content = re.sub(u'\u2014','',content)
#This is other part of code
htmlcontent = BeautifulSoup(content,"html.parser")

for cont in htmlcontent.select('p'):
    if cont.has_attr('class') == False:
        print(cont.strip()) #Returns an error as text contains long dash

任何想法如何从字符串中过滤掉长破折号以便与其他文本一起使用?我可以用短破折号替换它或完全删除,它们对我来说并不重要。

谢谢!

解答

您应该在使用 bs4 提取数据后清理数据:

  1. BS4会转换一些HTML实体,你不需要自己做。

  2. BS4 将为您解码文件

```

response = urllib.request.urlopen('website-im-opening')

content = response.read()

htmlcontent = BeautifulSoup(content,"html.parser")

for cont in htmlcontent.find_all('p', class_=False):

    print(p.text)

```

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐