最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python ET.parse 模塊功能詳解

 更新時間:2026年02月10日 09:31:57   作者:Yorlen_Zhang  
xml.etree.ElementTree(通常簡稱為 ET)是Python標準庫中用于解析和創(chuàng)建XML數據的模塊,本文給大家介紹Python ET.parse 模塊功能,感興趣的朋友跟隨小編一起看看吧

什么是 ElementTree

xml.etree.ElementTree(通常簡稱為 ET)是 Python 標準庫中用于解析和創(chuàng)建 XML 數據的模塊。它提供了輕量級、高效的 API,適合處理小到中等規(guī)模的 XML 文檔。

為什么選擇 ET?

  • ? Python 內置,無需安裝
  • ? 簡單易用的 API 設計
  • ? 內存效率高(迭代解析)
  • ? 支持 XPath 表達式查找元素

基礎概念:XML 結構

在深入學習之前,先了解 XML 的基本結構:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 這是注釋 -->
<library>                          <!-- 根元素 -->
    <book id="001">                <!-- 元素 + 屬性 -->
        <title>Python編程</title>   <!-- 子元素 -->
        <author>張三</author>
        <price>59.00</price>
    </book>
</library>

核心概念:

  • Element(元素):XML 標簽,如 <book>
  • Tag(標簽名):元素的名稱,如 "book"
  • Attribute(屬性):元素的特征,如 id="001"
  • Text(文本內容):元素內的文本,如 "Python編程"
  • Tail(尾部文本):結束標簽后的文本(較少使用)

解析 XML 文件

1. 基本解析方法

ET 提供了兩種主要解析方式:

import xml.etree.ElementTree as ET
# 方法1:解析文件(推薦用于文件)
tree = ET.parse('books.xml')  # 返回 ElementTree 對象
root = tree.getroot()         # 獲取根元素
# 方法2:解析字符串(用于從網絡或內存讀取)
xml_string = """<?xml version="1.0"?>
<library>
    <book id="001">
        <title>Python編程</title>
    </book>
</library>"""
root = ET.fromstring(xml_string)  # 直接返回根元素

2. 完整解析示例

假設我們有如下 books.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<library location="北京">
    <book id="001" category="編程">
        <title>Python編程:從入門到實踐</title>
        <author>埃里克·馬瑟斯</author>
        <price currency="CNY">89.00</price>
        <publish_date>2020-05</publish_date>
    </book>
    <book id="002" category="小說">
        <title>百年孤獨</title>
        <author>加西亞·馬爾克斯</author>
        <price currency="CNY">55.00</price>
        <publish_date>2011-06</publish_date>
    </book>
    <book id="003" category="編程">
        <title>流暢的Python</title>
        <author>盧西亞諾·拉馬略</author>
        <price currency="CNY">139.00</price>
        <publish_date>2017-05</publish_date>
    </book>
</library>

解析代碼:

import xml.etree.ElementTree as ET
def parse_library():
    """解析圖書館 XML 文件"""
    try:
        # 解析 XML 文件
        tree = ET.parse('books.xml')
        root = tree.getroot()
        print(f"根元素標簽: {root.tag}")
        print(f"根元素屬性: {root.attrib}")
        print(f"子元素數量: {len(root)}")
        print("-" * 50)
        # 遍歷所有 book 元素
        for book in root.findall('book'):
            book_id = book.get('id')           # 獲取屬性
            category = book.get('category')
            title = book.find('title').text    # 獲取文本內容
            author = book.find('author').text
            price_elem = book.find('price')
            price = price_elem.text
            currency = price_elem.get('currency')
            print(f"圖書ID: {book_id}")
            print(f"類別: {category}")
            print(f"書名: {title}")
            print(f"作者: {author}")
            print(f"價格: {currency} {price}")
            print("-" * 50)
    except ET.ParseError as e:
        print(f"XML 解析錯誤: {e}")
    except FileNotFoundError:
        print("文件未找到,請確保 books.xml 存在")
if __name__ == "__main__":
    parse_library()

輸出結果:

根元素標簽: library
根元素屬性: {'location': '北京'}
子元素數量: 3
--------------------------------------------------
圖書ID: 001
類別: 編程
書名: Python編程:從入門到實踐
作者: 埃里克·馬瑟斯
價格: CNY 89.00
--------------------------------------------------
...

遍歷 XML 樹

1. 迭代遍歷(內存友好)

對于大型 XML 文件,使用迭代器避免一次性加載所有數據:

import xml.etree.ElementTree as ET
def iterate_xml():
    """使用迭代器遍歷大型 XML"""
    # iterparse 在解析時生成事件,適合大文件
    context = ET.iterparse('books.xml', events=('start', 'end'))
    context = iter(context)
    event, root = next(context)
    book_count = 0
    for event, elem in context:
        # 'start' 事件:元素開始
        # 'end' 事件:元素結束(此時元素已完整)
        if event == 'end' and elem.tag == 'book':
            book_count += 1
            title = elem.find('title').text
            print(f"處理第 {book_count} 本書: {title}")
            # 處理完后清除元素釋放內存
            elem.clear()
            root.clear()
    print(f"總共處理了 {book_count} 本書")
# 遞歸遍歷所有元素
def recursive_walk(element, level=0):
    """遞歸打印 XML 結構"""
    indent = "  " * level
    print(f"{indent}<{element.tag}> {element.attrib if element.attrib else ''}")
    if element.text and element.text.strip():
        print(f"{indent}  文本: {element.text.strip()}")
    for child in element:
        recursive_walk(child, level + 1)
    print(f"{indent}</{element.tag}>")
# 使用示例
tree = ET.parse('books.xml')
recursive_walk(tree.getroot())

2. 按層級遍歷

def traverse_by_level(root):
    """按層級遍歷(廣度優(yōu)先)"""
    from collections import deque
    queue = deque([(root, 0)])
    while queue:
        elem, level = queue.popleft()
        indent = "  " * level
        print(f"{indent}[{level}] {elem.tag}: {elem.attrib}")
        for child in elem:
            queue.append((child, level + 1))
traverse_by_level(tree.getroot())

查找元素

ET 支持有限的 XPath 表達式,非常實用:

import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
# 1. find() - 查找第一個匹配的直接子元素
first_book = root.find('book')
print(f"第一本書: {first_book.find('title').text}")
# 2. findall() - 查找所有匹配的直接子元素
all_books = root.findall('book')
print(f"圖書總數: {len(all_books)}")
# 3. iter() - 遞歸查找所有指定標簽
all_prices = root.iter('price')
print("所有價格:")
for price in all_prices:
    print(f"  {price.text} {price.get('currency')}")
# 4. 帶條件的查找(XPath 語法)
# 查找 category="編程" 的所有圖書
programming_books = root.findall(".//book[@category='編程']")
print(f"\n編程類圖書數量: {len(programming_books)}")
# 5. 復雜 XPath 示例
# 查找價格大于 100 的圖書(需要遍歷判斷)
expensive_books = []
for book in root.findall('book'):
    price = float(book.find('price').text)
    if price > 100:
        expensive_books.append(book.find('title').text)
print(f"高價圖書: {expensive_books}")
# 6. 查找特定路徑
# 查找第一個 book 下的 title
title = root.find('./book[1]/title')
print(f"第一本書書名: {title.text}")

支持的 XPath 語法:

語法說明
tag選擇直接子元素
*匹配所有子元素
.當前元素
//遞歸查找所有后代
..父元素
[@attrib]有某屬性的元素
[@attrib='value']屬性等于某值的元素
[tag]有某子元素的元素
[position]第 N 個元素(從1開始)

獲取元素數據

完整的數據提取工具類

import xml.etree.ElementTree as ET
from dataclasses import dataclass
from typing import List, Optional, Dict
@dataclass
class Book:
    """圖書數據類"""
    id: str
    category: str
    title: str
    author: str
    price: float
    currency: str
    publish_date: str
class XMLExtractor:
    """XML 數據提取器"""
    def __init__(self, xml_file: str):
        self.tree = ET.parse(xml_file)
        self.root = self.tree.getroot()
    def get_root_info(self) -> Dict:
        """獲取根元素信息"""
        return {
            'tag': self.root.tag,
            'attributes': dict(self.root.attrib),
            'children_count': len(self.root)
        }
    def extract_all_books(self) -> List[Book]:
        """提取所有圖書信息"""
        books = []
        for book_elem in self.root.findall('book'):
            book = Book(
                id=book_elem.get('id', ''),
                category=book_elem.get('category', ''),
                title=self._get_text(book_elem, 'title'),
                author=self._get_text(book_elem, 'author'),
                price=float(self._get_text(book_elem, 'price')),
                currency=book_elem.find('price').get('currency', 'CNY'),
                publish_date=self._get_text(book_elem, 'publish_date')
            )
            books.append(book)
        return books
    def _get_text(self, parent: ET.Element, tag: str, default: str = '') -> str:
        """安全獲取子元素文本"""
        elem = parent.find(tag)
        return elem.text if elem is not None else default
    def get_books_by_category(self, category: str) -> List[Dict]:
        """按類別篩選圖書"""
        results = []
        xpath = f".//book[@category='{category}']"
        for book in self.root.findall(xpath):
            results.append({
                'id': book.get('id'),
                'title': book.find('title').text,
                'author': book.find('author').text
            })
        return results
    def get_statistics(self) -> Dict:
        """獲取統(tǒng)計信息"""
        books = self.extract_all_books()
        if not books:
            return {}
        prices = [b.price for b in books]
        categories = {}
        for b in books:
            categories[b.category] = categories.get(b.category, 0) + 1
        return {
            'total_books': len(books),
            'avg_price': sum(prices) / len(prices),
            'max_price': max(prices),
            'min_price': min(prices),
            'categories': categories
        }
# 使用示例
if __name__ == "__main__":
    extractor = XMLExtractor('books.xml')
    print("=== 根元素信息 ===")
    print(extractor.get_root_info())
    print("\n=== 所有圖書 ===")
    for book in extractor.extract_all_books():
        print(f"{book.id}: {book.title} ({book.author}) - {book.currency}{book.price}")
    print("\n=== 編程類圖書 ===")
    print(extractor.get_books_by_category('編程'))
    print("\n=== 統(tǒng)計信息 ===")
    stats = extractor.get_statistics()
    print(f"圖書總數: {stats['total_books']}")
    print(f"平均價格: ¥{stats['avg_price']:.2f}")
    print(f"價格區(qū)間: ¥{stats['min_price']:.2f} - ¥{stats['max_price']:.2f}")
    print(f"類別分布: {stats['categories']}")

修改 XML

1. 修改現有元素

import xml.etree.ElementTree as ET
def modify_xml():
    """修改 XML 內容"""
    tree = ET.parse('books.xml')
    root = tree.getroot()
    # 1. 修改屬性
    root.set('updated', '2024-01-01')
    root.set('location', '上海')  # 修改現有屬性
    # 2. 修改元素文本
    for book in root.findall('book'):
        price_elem = book.find('price')
        old_price = float(price_elem.text)
        # 打 8 折
        new_price = old_price * 0.8
        price_elem.text = f"{new_price:.2f}"
        price_elem.set('discount', '0.8')
    # 3. 添加新元素
    for book in root.findall('book'):
        stock = ET.SubElement(book, 'stock')
        stock.text = '100'
        stock.set('warehouse', 'A1')
    # 4. 刪除元素
    # 刪除第一本書的 publish_date
    first_book = root.find('book')
    publish_date = first_book.find('publish_date')
    if publish_date is not None:
        first_book.remove(publish_date)
    # 5. 保存修改
    tree.write('books_modified.xml', 
               encoding='utf-8', 
               xml_declaration=True,
               short_empty_elements=False)
    print("修改完成,已保存到 books_modified.xml")
modify_xml()

2. 批量修改工具

class XMLModifier:
    """XML 批量修改器"""
    def __init__(self, input_file: str):
        self.tree = ET.parse(input_file)
        self.root = self.tree.getroot()
        self.modified = False
    def update_prices(self, increase_rate: float = 0.1):
        """批量更新價格"""
        for price_elem in self.root.iter('price'):
            old_price = float(price_elem.text)
            new_price = old_price * (1 + increase_rate)
            price_elem.text = f"{new_price:.2f}"
            price_elem.set('updated', 'true')
        self.modified = True
        print(f"已更新所有價格,漲幅 {increase_rate*100}%")
    def add_element_to_all(self, tag: str, text: str, attrib: dict = None):
        """為所有 book 添加子元素"""
        attrib = attrib or {}
        for book in self.root.findall('book'):
            elem = ET.SubElement(book, tag, attrib)
            elem.text = text
        self.modified = True
        print(f"已為所有圖書添加 <{tag}> 元素")
    def remove_element_by_tag(self, tag: str):
        """刪除所有指定標簽的元素"""
        count = 0
        for parent in self.root.iter():
            for child in list(parent):  # 使用 list 避免迭代時修改
                if child.tag == tag:
                    parent.remove(child)
                    count += 1
        self.modified = True
        print(f"已刪除 {count} 個 <{tag}> 元素")
    def save(self, output_file: str = None):
        """保存文件"""
        if not self.modified:
            print("沒有修改需要保存")
            return
        output = output_file or 'modified.xml'
        self.tree.write(output, 
                       encoding='utf-8',
                       xml_declaration=True)
        print(f"已保存到: {output}")
# 使用示例
modifier = XMLModifier('books.xml')
modifier.update_prices(0.15)  # 漲價 15%
modifier.add_element_to_all('status', '在售', {'available': 'true'})
modifier.save('books_updated.xml')

創(chuàng)建 XML

1. 從零創(chuàng)建 XML

import xml.etree.ElementTree as ET
from datetime import datetime
def create_library_xml():
    """創(chuàng)建圖書館 XML 文件"""
    # 創(chuàng)建根元素
    root = ET.Element('library')
    root.set('version', '1.0')
    root.set('created', datetime.now().isoformat())
    # 添加注釋
    comment = ET.Comment(' 這是一個自動生成的圖書館數據文件 ')
    root.append(comment)
    # 創(chuàng)建圖書數據
    books_data = [
        {
            'id': '004',
            'category': '科幻',
            'title': '三體',
            'author': '劉慈欣',
            'price': '98.00',
            'currency': 'CNY',
            'tags': ['雨果獎', '科幻經典', '系列作品']
        },
        {
            'id': '005',
            'category': '技術',
            'title': '深度學習',
            'author': '伊恩·古德費洛',
            'price': '168.00',
            'currency': 'CNY',
            'tags': ['AI', '機器學習', '教材']
        }
    ]
    for book_data in books_data:
        # 創(chuàng)建 book 元素
        book = ET.SubElement(root, 'book')
        book.set('id', book_data['id'])
        book.set('category', book_data['category'])
        # 添加子元素
        title = ET.SubElement(book, 'title')
        title.text = book_data['title']
        author = ET.SubElement(book, 'author')
        author.text = book_data['author']
        price = ET.SubElement(book, 'price')
        price.text = book_data['price']
        price.set('currency', book_data['currency'])
        # 添加標簽列表
        tags = ET.SubElement(book, 'tags')
        for tag_text in book_data['tags']:
            tag = ET.SubElement(tags, 'tag')
            tag.text = tag_text
    # 創(chuàng)建 ElementTree 對象
    tree = ET.ElementTree(root)
    # 美化輸出(縮進)
    ET.indent(tree, space='    ', level=0)
    # 保存到文件
    tree.write('new_library.xml', 
               encoding='utf-8',
               xml_declaration=True,
               short_empty_elements=False)
    print("成功創(chuàng)建 new_library.xml")
    # 同時返回字符串形式
    return ET.tostring(root, encoding='unicode')
xml_string = create_library_xml()
print("\n生成的 XML 內容:")
print(xml_string)

生成的 XML 結構:

<?xml version='1.0' encoding='utf-8'?>
<library created="2024-01-15T10:30:00" version="1.0">
    <!-- 這是一個自動生成的圖書館數據文件 -->
    <book category="科幻" id="004">
        <title>三體</title>
        <author>劉慈欣</author>
        <price currency="CNY">98.00</price>
        <tags>
            <tag>雨果獎</tag>
            <tag>科幻經典</tag>
            <tag>系列作品</tag>
        </tags>
    </book>
    ...
</library>

2. 使用 Element 工廠函數

def create_element_factory():
    """使用工廠模式創(chuàng)建 XML"""
    def create_book(id, title, author, **kwargs):
        """創(chuàng)建圖書元素的工廠函數"""
        book = ET.Element('book', {'id': id})
        ET.SubElement(book, 'title').text = title
        ET.SubElement(book, 'author').text = author
        for key, value in kwargs.items():
            if isinstance(value, dict):
                # 帶屬性的元素
                elem = ET.SubElement(book, key, value.get('attrib', {}))
                elem.text = value.get('text', '')
            else:
                ET.SubElement(book, key).text = str(value)
        return book
    # 構建 XML
    root = ET.Element('catalog')
    book1 = create_book(
        '006', 
        'Python數據科學手冊',
        '杰克·萬托布拉斯',
        price={'text': '128.00', 'attrib': {'currency': 'CNY'}},
        publisher='人民郵電出版社',
        year='2020'
    )
    root.append(book1)
    # 保存
    tree = ET.ElementTree(root)
    ET.indent(tree, space='  ')
    tree.write('catalog.xml', encoding='utf-8', xml_declaration=True)
    print("創(chuàng)建 catalog.xml 成功")
create_element_factory()

實際應用案例

案例1:配置文件管理器

import xml.etree.ElementTree as ET
import os
class ConfigManager:
    """XML 配置文件管理器"""
    CONFIG_FILE = 'app_config.xml'
    def __init__(self):
        self.tree = None
        self.root = None
        self._load_or_create()
    def _load_or_create(self):
        """加載或創(chuàng)建配置文件"""
        if os.path.exists(self.CONFIG_FILE):
            self.tree = ET.parse(self.CONFIG_FILE)
            self.root = self.tree.getroot()
        else:
            self.root = ET.Element('configuration')
            self.root.set('version', '1.0')
            self.tree = ET.ElementTree(self.root)
            self._save()
    def _save(self):
        """保存配置"""
        ET.indent(self.tree, space='    ')
        self.tree.write(self.CONFIG_FILE, encoding='utf-8', xml_declaration=True)
    def get(self, section: str, key: str, default=None):
        """獲取配置值"""
        section_elem = self.root.find(f".//section[@name='{section}']")
        if section_elem is None:
            return default
        item = section_elem.find(f"item[@key='{key}']")
        if item is None:
            return default
        return item.get('value')
    def set(self, section: str, key: str, value: str):
        """設置配置值"""
        section_elem = self.root.find(f".//section[@name='{section}']")
        if section_elem is None:
            section_elem = ET.SubElement(self.root, 'section')
            section_elem.set('name', section)
        item = section_elem.find(f"item[@key='{key}']")
        if item is None:
            item = ET.SubElement(section_elem, 'item')
            item.set('key', key)
        item.set('value', str(value))
        self._save()
    def get_database_config(self) -> dict:
        """獲取數據庫配置"""
        return {
            'host': self.get('database', 'host', 'localhost'),
            'port': int(self.get('database', 'port', '3306')),
            'username': self.get('database', 'username', 'root'),
            'password': self.get('database', 'password', ''),
            'database': self.get('database', 'database', 'test')
        }
# 使用示例
config = ConfigManager()
config.set('database', 'host', '192.168.1.100')
config.set('database', 'port', '5432')
config.set('app', 'debug', 'true')
print(config.get_database_config())

案例2:數據轉換器(CSV 轉 XML)

import csv
import xml.etree.ElementTree as ET
from datetime import datetime
def csv_to_xml(csv_file: str, xml_file: str, root_tag: str = 'data'):
    """將 CSV 文件轉換為 XML"""
    root = ET.Element(root_tag)
    root.set('generated', datetime.now().isoformat())
    root.set('source', csv_file)
    with open(csv_file, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for i, row in enumerate(reader, 1):
            record = ET.SubElement(root, 'record')
            record.set('id', str(i))
            for key, value in row.items():
                # 清理標簽名(XML 標簽不能以數字開頭,不能包含空格)
                clean_key = key.strip().replace(' ', '_')
                if clean_key[0].isdigit():
                    clean_key = 'f_' + clean_key
                field = ET.SubElement(record, clean_key)
                field.text = value
    # 美化并保存
    tree = ET.ElementTree(root)
    ET.indent(tree, space='    ')
    tree.write(xml_file, encoding='utf-8', xml_declaration=True)
    print(f"成功轉換: {csv_file} -> {xml_file}")
# 示例 CSV 內容:
# name,age,city
# 張三,28,北京
# 李四,32,上海
# csv_to_xml('data.csv', 'output.xml')

常見錯誤與解決方案

1. 編碼問題

# ? 錯誤:默認編碼可能不支持中文
tree.write('output.xml')
# ? 正確:指定 UTF-8 編碼
tree.write('output.xml', encoding='utf-8', xml_declaration=True)

2. 命名空間處理

# 處理帶命名空間的 XML
xml_with_ns = """<?xml version="1.0"?>
<root xmlns:ns="http://example.com/ns">
    <ns:item>內容</ns:item>
</root>"""
root = ET.fromstring(xml_with_ns)
# 方法1:使用完整標簽名
for elem in root.findall('{http://example.com/ns}item'):
    print(elem.text)
# 方法2:定義命名空間字典
namespaces = {'ns': 'http://example.com/ns'}
for elem in root.findall('ns:item', namespaces):
    print(elem.text)

3. 大小寫敏感

# XML 是大小寫敏感的
root.find('Book')  # 找不到 <book>
root.find('book')  # 正確

4. 內存優(yōu)化

# 大文件處理(>100MB)
# ? 錯誤:一次性加載
tree = ET.parse('huge.xml')
# ? 正確:迭代解析
for event, elem in ET.iterparse('huge.xml', events=('end',)):
    if elem.tag == 'record':
        process(elem)
        elem.clear()  # 釋放內存

5. 特殊字符轉義

# ET 自動處理特殊字符
root = ET.Element('test')
root.text = '<特殊內容> & "引號"'
# 輸出: &lt;特殊內容&gt; &amp; &quot;引號&quot;

總結

功能方法說明
解析文件ET.parse()返回 ElementTree
解析字符串ET.fromstring()返回根元素
查找單個element.find()第一個匹配
查找多個element.findall()所有直接子元素
遞歸查找element.iter()所有后代元素
獲取屬性element.get()獲取屬性值
獲取文本element.text元素內容
創(chuàng)建子元素ET.SubElement()工廠函數
保存文件tree.write()寫入文件

最佳實踐建議:

  • 始終指定 encoding='utf-8' 保存中文
  • 大文件使用 iterparse() 迭代處理
  • 使用 try-except 捕獲 ParseError
  • 復雜查詢考慮使用 lxml 庫(支持完整 XPath)
  • 修改前先備份原文件

通過本教程的學習,您已經掌握了 Python ET 模塊的核心功能,可以處理絕大多數 XML 數據操作需求。建議動手實踐每個示例代碼,加深理解。

到此這篇關于Python ET.parse 模塊功能詳解的文章就介紹到這了,更多相關Python ET.parse內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python?DataFrame中stack()方法、unstack()方法和pivot()方法淺析

    python?DataFrame中stack()方法、unstack()方法和pivot()方法淺析

    這篇文章主要給大家介紹了關于python?DataFrame中stack()方法、unstack()方法和pivot()方法的相關資料,pandas中這三種方法都是用來對表格進行重排的,其中stack()是unstack()的逆操作,需要的朋友可以參考下
    2022-04-04
  • python實現一行輸入多個值和一行輸出多個值的例子

    python實現一行輸入多個值和一行輸出多個值的例子

    今天小編就為大家分享一篇python實現一行輸入多個值和一行輸出多個值的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python檢索特定內容的文本文件實例

    python檢索特定內容的文本文件實例

    今天小編就為大家分享一篇python檢索特定內容的文本文件實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • 在pytorch中計算準確率,召回率和F1值的操作

    在pytorch中計算準確率,召回率和F1值的操作

    這篇文章主要介紹了在pytorch中計算準確率,召回率和F1值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • 一文詳細介紹numpy在python中的用法

    一文詳細介紹numpy在python中的用法

    這篇文章主要介紹了numpy在python中的用法,NumPy是Python科學計算庫,主要用于處理大型多維數組和矩陣運算,它提供了多種函數進行數組操作,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-01-01
  • python使用wxPython打開并播放wav文件的方法

    python使用wxPython打開并播放wav文件的方法

    這篇文章主要介紹了python使用wxPython打開并播放wav文件的方法,涉及Python操作音頻文件的相關技巧,需要的朋友可以參考下
    2015-04-04
  • Python簡單實現安全開關文件的兩種方式

    Python簡單實現安全開關文件的兩種方式

    這篇文章主要介紹了Python簡單實現安全開關文件的兩種方式,涉及Python的try語句針對錯誤的判定與捕捉相關技巧,需要的朋友可以參考下
    2016-09-09
  • 一文帶你掌握Matplotlib圖形繪制

    一文帶你掌握Matplotlib圖形繪制

    Matplotlib是一個基于Python的繪圖庫,它提供了一整套與Matlab相似的命令API,非常適合交互式繪圖,這篇文章主要給大家介紹了關于Matplotlib圖形繪制的相關資料,需要的朋友可以參考下
    2023-09-09
  • 一文教你徹底掌握Python數據類型轉換

    一文教你徹底掌握Python數據類型轉換

    Python的核心數據類型包括:int(整數),float(浮點數),str(字符串),bool(布爾值),本文整理了他們之前相互轉換的方法,需要的可以了解下
    2025-05-05
  • 利用Python抓取網頁數據的多種方式與示例詳解

    利用Python抓取網頁數據的多種方式與示例詳解

    在數據科學和網絡爬蟲領域,網頁數據抓取是非常重要的一項技能,Python 是進行網頁抓取的流行語言,因為它擁有強大的第三方庫,能夠簡化網頁解析和數據提取的過程,本篇文章將介紹幾種常見的網頁數據抓取方法,需要的朋友可以參考下
    2025-04-04

最新評論

蓝田县| 邵阳市| 石林| 宜阳县| 渝北区| 涟水县| 嘉定区| 三门峡市| 三门县| 无锡市| 张家口市| 镇雄县| 安新县| 云浮市| 绩溪县| 达拉特旗| 攀枝花市| 古交市| 榆树市| 平舆县| 米林县| 西乌| 康乐县| 辰溪县| 龙山县| 广东省| 津市市| 弥渡县| 沁水县| 宁晋县| 礼泉县| 晋州市| 诸城市| 三都| 额尔古纳市| 和静县| 玉环县| 澳门| 武定县| 赤水市| 禄劝|