我使用第三方工具输出Unicode格式的文件.但是,我更喜欢它是ASCII.该工具没有更改文件格式的设置.
使用Python转换整个文件格式的最佳方法是什么?
在网页抓取过程中以及在删除所有html标签之后,我在unicode(☎)中获得了黑色电话字符\ u260e.但与此不同的是,我确实希望摆脱它.
我在Scrapy中使用以下正则表达式来消除html标记:
pattern = re.compile("<.*?>| |&",re.DOTALL|re.M)
Run Code Online (Sandbox Code Playgroud)
然后我试图匹配\ u260e,我想我被反斜杠瘟疫抓住了.我试过这种模式失败了:
pattern = re.compile("<.*?>| |&|\u260e",re.DOTALL|re.M)
pattern = re.compile("<.*?>| |&|\\u260e",re.DOTALL|re.M)
pattern = re.compile("<.*?>| |&|\\\\u260e",re.DOTALL|re.M)
Run Code Online (Sandbox Code Playgroud)
这些都不起作用,我仍然有作为输出的\ u260e.我怎么能让它消失?
使用BeautifulSoup 3.1.0.1和Python 2.5.2,并尝试用法语解析网页.但是,一旦我调用findAll,我就会收到以下错误:
UnicodeEncodeError:'ascii'编解码器无法对位置1146中的字符u'\ xe9'进行编码:序数不在范围内(128)
以下是我目前正在运行的代码:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html")
soup = BeautifulSoup(page, fromEncoding="latin1")
r = soup.findAll("table")
print r
Run Code Online (Sandbox Code Playgroud)
有人知道为什么吗?
谢谢!
更新:如果被请求,下面是完整的回溯
Traceback (most recent call last):
File "[...]\test.py", line 6, in <module>
print r
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud) 我已经把这个问题搞砸了好几个小时,我似乎无法深究它.我已经详细浏览了这个网站,虽然其他人似乎有类似的问题,但他们给出的解决方案对我不起作用.
我有一个python脚本,它读取网站的HTML并使用漂亮的汤来查找头部,正文,H1等等...然后将它们存储在utf-8 MySQL表中.
看起来很直接,但我一直遇到:
UnicodeDecodeError: 'ascii' codec can't decode byte xxxxxx
Run Code Online (Sandbox Code Playgroud)
当我编码.我已经尝试了所有我能找到的东西来阻止这种情况发生但无济于事.这是代码的一个版本:
soup = BeautifulSoup(strIndexPage)
strIndexPageBody = str(soup.body)
strIndexPageBody = strIndexPageBody.encode('ascii', 'ignore') # I know ignore is not best practice but I am really not interested in anything outside the ascii character set
strIndexPageBody = strIndexPageBody .replace('"','"')
strIndexPageBody = strIndexPageBody .replace("'","&rsquo")
Run Code Online (Sandbox Code Playgroud)
我尝试转换为utf-8的早期版本效果更好,但我最终得到了
`
Run Code Online (Sandbox Code Playgroud)
某些HTML中出现的字符会破坏MySQL的插入/更新.显然我已经尝试搜索这个角色并替换它,但是python告诉我在我的代码中有一个非ascii字符!
我读过很多篇文章,说我应该首先看一下HTML的编码,解码然后编码以适应,但编码并不总是从BS回来,和/或没有在HTML中声明.
我相信有一个简单的方法,但我找不到它.
谢谢你的帮助.