一、什麼是數據解析
數據解析是指將一些結構化或半結構化數據從一種形式轉換為另一種形式的過程。其中結構化數據與半結構化數據是指具有非常明顯固定格式的數據,例如XML、JSON等;而非結構化數據則是指不具有固定格式的數據,例如文本、圖片等。
一般來說,數據解析的目的是將源數據轉換為能夠被程序進一步處理的形式,或將數據以一種更易於人們所理解的形式展現出來。
Python是一種非常適合進行數據解析的語言,Python有着強大的第三方模塊支持,使得解析數據變得非常簡單。如:BeautifulSoup、lxml等。
二、常用的數據解析方法
1、使用正則表達式
import re
src = 'name:張三 age:20'
pattern = 'name:(?P<name>.+?)\sage:(?P<age>\d+)'
match = re.search(pattern, src)
if match:
print(match.group('name'), match.group('age'))
2、使用BeautifulSoup
import requests
from bs4 import BeautifulSoup
html = requests.get('http://www.baidu.com')
bs = BeautifulSoup(html.content, 'html.parser')
print(bs.title.string)
3、使用lxml
import requests
from lxml import etree
html = requests.get('http://www.baidu.com')
selector = etree.HTML(html.content)
title = selector.xpath('//title/text()')[0]
print(title)
三、實例:解析XML數據
我們有一個XML數據結構,如下:
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
</country>
</data>
我們要將這個XML數據解析出來,可以使用ElementTree庫來完成:
import xml.etree.ElementTree as ET
data = '''
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
</country>
</data>
'''
root = ET.fromstring(data)
for country in root.findall('country'):
name = country.get('name')
rank = country.find('rank').text
year = country.find('year').text
gdppc = country.find('gdppc').text
print(name, rank, year, gdppc)
四、結語
數據解析是Python編程中非常重要的一個環節,Python不僅提供了多種解析數據的方式,還有很多實用的第三方庫,可以為數據處理提供強有力的支持。
完整代碼如下:
import xml.etree.ElementTree as ET
import re
import requests
from bs4 import BeautifulSoup
from lxml import etree
# 使用正則表達式解析數據
src = 'name:張三 age:20'
pattern = 'name:(?P<name>.+?)\sage:(?P<age>\d+)'
match = re.search(pattern, src)
if match:
print(match.group('name'), match.group('age'))
# 使用BeautifulSoup解析HTML數據
html = requests.get('http://www.baidu.com')
bs = BeautifulSoup(html.content, 'html.parser')
print(bs.title.string)
# 使用lxml解析HTML數據
html = requests.get('http://www.baidu.com')
selector = etree.HTML(html.content)
title = selector.xpath('//title/text()')[0]
print(title)
# 使用ElementTree解析XML數據
data = '''
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
</country>
</data>
'''
root = ET.fromstring(data)
for country in root.findall('country'):
name = country.get('name')
rank = country.find('rank').text
year = country.find('year').text
gdppc = country.find('gdppc').text
print(name, rank, year, gdppc)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243737.html