【问题标题】:How to remove nonAscii characters in python如何在python中删除非ASCII字符
【发布时间】:2015-10-21 15:45:27
【问题描述】:

这是我的代码:

#!C:/Python27/python
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import urllib2
import sys
import urlparse
import io

url = "http://www.dlib.org/dlib/november14/beel/11beel.html"
#url = "http://eqa.unibo.it/article/view/4554"
#r = requests.get(url)
html = urllib2.urlopen(url)
soup = BeautifulSoup(html, "html.parser")
#soup = BeautifulSoup(r.text,'lxml')

if url.find("http://www.dlib.org") != -1:
    div = soup.find('td', valign='top')
else:
    div = soup.find('div',id='content')

f = open('path/file_name.html', 'w')
f.write(str(div))
f.close()

抓取那些网页,我发现一些非AScii 字符到从该脚本编写的html 文件中,我需要将其删除或解析为可读字符。 有什么建议吗?谢谢

【问题讨论】:

  • 你写的脚本没有报错,非ascii字母有什么问题?,你现在要在你写的文件里吗?
  • 我知道没有错误,但我需要删除 HTML 中的一些字符,例如“”。
  • @Poggio 可能会有所帮助stackoverflow.com/questions/17732695/…

标签: python html character-encoding web-scraping beautifulsoup


【解决方案1】:

尝试规范化字符串,然后ASCII 对其进行编码,忽略错误。

# -*- coding: utf-8 -*-
from unicodedata import normalize

string = 'úäô§'

if isinstance(string, str):
    string = string.decode('utf-8')

print normalize('NFKD', string).encode('ASCII', 'ignore')
>>> uao

【讨论】:

  • 我认为你的解决方案是最好的,因为我的解决方案对 16 位编码的字母做了一些奇怪的事情,而你的表现稍微更理智
【解决方案2】:

字符为 8 字节 (0-255),ascii 字符为 7 字节 (0-127),因此您可以简单地删除 ord 值低于 128 的所有字符

chr 将整数转换为字符,ord 将字符转换为整数。

text = ''.join((c for c in str(div) if ord(c) < 128)

这应该是你的最终代码

#!C:/Python27/python
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import urllib2
import sys
import urlparse
import io

url = "http://www.dlib.org/dlib/november14/beel/11beel.html"
#url = "http://eqa.unibo.it/article/view/4554"
#r = requests.get(url)
html = urllib2.urlopen(url)
soup = BeautifulSoup(html, "html.parser")
#soup = BeautifulSoup(r.text,'lxml')

if url.find("http://www.dlib.org") != -1:
    div = soup.find('td', valign='top')
else:
    div = soup.find('div',id='content')

f = open('path/file_name.html', 'w')
text = ''.join((c for c in str(div) if ord(c) < 128)
f.write(text)
f.close()

【讨论】:

  • Traceback(最近一次调用最后一次):文件“pppp.py”,第 38 行,在 中 div = ''.join((c for c in div if ord(c) 中 div = ''.join((c for c in div if ord(c)
  • 应该有个str(div),把div标签转成文本串,我忘了
  • 我需要以更好的方式处理一些字符,就像强调字母一样。例如:à - è - ì - ò - ù,我需要与其余文本一起打印。不知道有没有解决办法?
【解决方案3】:

从文本中删除非ASCII 字符。

import string

text = [word for word in text if word not in string.ascii_letters]

【讨论】:

  • 这会引发错误,因为我无法将 nonAscii char 写入 Python。
  • @Poggio 你不能运行这个列表理解吗?您遇到了什么错误?
猜你喜欢
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 2011-02-14
相关资源
最近更新 更多