【发布时间】:2016-11-27 21:45:40
【问题描述】:
所以,每次我在 oed.com 上抓取这个网页时,我都会得到一些似乎是 unicode 字符的小撇号。如何过滤我的代码并用普通撇号替换所有这些字符?下面是我用来打印单词列表的代码(如果你没有登录网站,多次抓取会显示重复的单词)。
import csv
import os
import re
import requests
import urllib2
year_start= 1550
year_end = 1560
subject_search = ['Law']
with open("/Applications/Python 3.5/Economic/OED_table.csv", 'a') as outputw, open("/Applications/Python 3.5/Economic/OED.html", 'a') as outputh: #opens the folder and 'a' adds the words to the csv file.
for year in range(year_start, year_end +1):
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
request = urllib2.Request('http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true&dateFilter='+ str(year)+ '&nearDistance=1&ordered=false&page=1&pageSize=100&scope=ENTRY&sort=entry&subjectClass='+ str(subject_search)+ '&type=dictionarysearch', None, header)
page = opener.open(request)
urlpage = page.read()
outputh.write(urlpage)
new_words = re.findall(r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print new_words
csv_writer = csv.writer(outputw)
if csv_writer.writerow([year] + new_words):
csv_writer.writerow([year, word])
在打印出我的文字后,我经常得到 unicode 字母 \xcb\x88。例如,单词 un'sentenced 打印为 'un\xcb\x88sentenced'。
如何获取这些 unicode 字母的所有实例并将它们替换为适当的撇号 > ' 。我在想它会是这样的,
for word in new_words:
word = re.sub('[\x00-\x7f]','', word)
但我被卡住了。
【问题讨论】:
-
您想删除这些字符还是将它们正确解释为 unicode?看看docs.python.org/2/howto/unicode.html。如果可能的话,我建议您切换到 Python 3,它在处理 unicode 方面要好得多。
-
@amyrit ,我想基本上删除字符并用简单的键盘撇号字符替换它们>'
-
你试过
word.replace('xcb\x88', "'")吗?不过,这只是解决了您的部分问题,我建议您正确处理 unicode。如果那是现实生活中的编码,你就无法避免。 -
@amyrit,啊,好的。我现在正在阅读文档。我是经济专业的,不是comp。科学。学生,所以总的来说,这些东西让我头疼。
-
没关系,unicode 是很多人的噩梦。如果可以,请使用 Python 3。
标签: python web-scraping python-unicode