gpt4 book ai didi

python - 从字符串中删除长破折号

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:39 25 4
gpt4 key购买 nike

我正在尝试将 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)

```

关于python - 从字符串中删除长破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42856795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com