在Python中進(jìn)行網(wǎng)頁爬取后,通常需要對(duì)獲取到的數(shù)據(jù)進(jìn)行清洗,以確保數(shù)據(jù)的準(zhǔn)確性和可用性。以下是一些常見的數(shù)據(jù)清洗步驟和技巧:
使用BeautifulSoup
或lxml
庫可以方便地去除HTML標(biāo)簽。
from bs4 import BeautifulSoup
html = """
<html>
<head><title>Example Page</title></head>
<body>
<h1>Welcome to Example Page</h1>
<p class="content">This is an example paragraph.</p>
</body>
</html>
"""
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
print(text)
使用正則表達(dá)式可以去除特殊字符和多余的空格。
import re
text = "This is an example paragraph. \n\t\r"
cleaned_text = re.sub(r'\s+', ' ', text).strip()
print(cleaned_text)
如果數(shù)據(jù)是以某種分隔符分隔的,可以使用split
方法進(jìn)行分割。
text = "apple,banana,orange"
fruits = text.split(',')
print(fruits)
使用列表推導(dǎo)式或filter
函數(shù)可以去除空值。
data = ["apple", "", "banana", None, "orange"]
filtered_data = [item for item in data if item]
print(filtered_data)
將字符串轉(zhuǎn)換為合適的數(shù)據(jù)類型,如整數(shù)、浮點(diǎn)數(shù)等。
data = ["1", "2.5", "three"]
numbers = [float(item) if item.isdigit() else None for item in data]
print(numbers)
使用正則表達(dá)式可以提取特定的數(shù)據(jù)。
import re
text = "The price of the item is $10.99."
price = re.search(r'\$(\d+\.\d{2})', text).group(1)
print(price)
將數(shù)據(jù)轉(zhuǎn)換為統(tǒng)一的格式,如統(tǒng)一大小寫、去除多余符號(hào)等。
data = ["Apple", "banana", " ORANGE "]
normalized_data = [item.strip().title() for item in data]
print(normalized_data)
pandas
庫提供了強(qiáng)大的數(shù)據(jù)清洗功能。
import pandas as pd
data = {
"Name": ["John", " Jane ", "Doe"],
"Age": ["25", "30", None],
"City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
# 去除空值
df = df.dropna()
# 轉(zhuǎn)換數(shù)據(jù)類型
df['Age'] = df['Age'].astype(int)
print(df)
numpy
庫可以進(jìn)行高效的數(shù)值計(jì)算和數(shù)組操作。
import numpy as np
data = np.array(["1", "2.5", "three"])
numeric_data = np.array([float(item) if item.isdigit() else np.nan for item in data])
print(numeric_data)
通過這些步驟和技巧,可以有效地清洗爬取到的數(shù)據(jù),確保其質(zhì)量和可用性。