Python网络数据采集7: 数据清洗

本文介绍了如何使用网络爬虫技术进行数据抓取,并详细解释了数据清洗的方法,包括使用Python进行n-gram分析和利用第三方工具OpenRefine进行数据标准化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    网站的真实故事其实都隐藏在JavaScript、登录表单和网站反抓取措施的背后。

    通过第二部分(7-14章)的内容的学习,你将掌握如何用网络爬虫测试网站,自动化处理,以及通过更多的方式接入网络。最后你将学到一些数据采集的工具,帮助你在不同的环境中收集和操作任意类型的网络数据,深入互联网的每个角落。

    由于错误的标点符号、大小写字母不一致、断行和拼写错误等问题,零乱的数据(dirty data)是网络中的大问题。

7.1 编写代码清洗数据

    在语言学里有一个模型叫n-gram,表示文字或语言中的n个连续的单词组成的序列。可以很容易地把一句话分解成若干个文字片段。

    下面的代码将返回维基百科词条“Python programming language”的 2-gram 列表:

# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup

def ngrams(input, n):
	input = input.split(' ')   # 分成单词序列,所有单词按照空格分开
	output = []
	for i in range(len(input) - n + 1):
		output.append(input[i:i+n])
	return output

html = urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)");
bsObj = BeautifulSoup(html)
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
print(ngrams)
print("2-grams count is: " + str(len(ngrams)))
不过,同时也会出现一些零乱的数据

# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import string

def cleanInput(input):
	input = re.sub('\n+', " ", input)           #把换行符替换成空格
	input = re.sub('\[[0-9]*\]', "", input)     #剔除[数字]
	input = re.sub(' +', " ", input)            #连续的多个空格替换成空格
	input = bytes(input, 'UTF-8')
	input = input.decode('ascii', 'ignore')
	cleanInput = []
	input = input.split(' ')   # 分成单词序列,所有单词按照空格分开
	for item in input:
		item = item.strip(string.punctuation)  # 所有的标点符号
		if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):    #删除单词a i
			cleanInput.append(item)
	return cleanInput

def ngrams(input, n):
	input = cleanInput(input)   # 分成单词序列,所有单词按照空格分开
	output = []
	for i in range(len(input) - n + 1):
		output.append(input[i:i+n])
	return output

html = urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)");
bsObj = BeautifulSoup(html)
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
print(ngrams)
print("2-grams count is: " + str(len(ngrams)))
    数据标准化:

7.2 数据存储后再清洗

   第三方工具OpenRefine    http://openrefine.org   不仅可以快速简单地清理数据,还可以让非编程人员轻松地看见和使用你的数据

   下载http://openrefine.org/download.html

    使用



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值