一、Python解析JSON
JSON是一種輕量級的數據交換格式,通過Python的json庫可以方便地進行解析。以下為示例代碼:
import json json_str = '{"name": "Tom", "age": 18, "gender": "male"}' json_dict = json.loads(json_str) print(json_dict['name'])
以上代碼將JSON字元串解析為Python字典,並且可以方便地訪問其中的數據。
二、Python解析XML
XML是一種描述數據的標記語言,通過Python的xml庫可以方便地進行解析。以下為示例代碼:
import xml.etree.ElementTree as ET xml_str = '<students><student id="001"><name>Tom</name><age>18</age></student></students>' root = ET.fromstring(xml_str) for child in root: print(child.attrib, child.find('name').text, child.find('age').text)
以上代碼將XML字元串解析為樹形結構,並且可以通過訪問元素和屬性來訪問其中的數據。
三、Python解析URL參數
URL參數是通過URL傳遞數據的方式,通過Python的urllib庫中的parse模塊可以方便地進行解析。以下為示例代碼:
import urllib.parse url = 'https://www.example.com/?name=Tom&age=18' params = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query) print(params['name'][0], params['age'][0])
以上代碼將URL參數解析為字典,並且可以方便地訪問其中的數據。
四、Python解析HTML
HTML是一種用於構建網頁的標記語言,通過Python的BeautifulSoup庫可以方便地進行解析。以下為示例代碼:
from bs4 import BeautifulSoup html_str = '<html><body><h1>Hello, World!</h1></body></html>' soup = BeautifulSoup(html_str, 'html.parser') print(soup.find('h1').text)
以上代碼將HTML字元串解析為樹形結構,並且可以通過訪問標籤和屬性來訪問其中的數據。
五、Python解析JSON文件
通過Python的json庫可以方便地解析JSON文件。以下為示例代碼:
import json with open('data.json', 'r') as f: json_dict = json.load(f) print(json_dict['name'])
以上代碼將JSON文件解析為Python字典,並且可以方便地訪問其中的數據。
六、Python解析INI文件
INI是一種簡單的配置文件格式,通過Python的ConfigParser庫可以方便地進行解析。以下為示例代碼:
import configparser config = configparser.ConfigParser() config.read('config.ini') print(config.get('Section1', 'key1'))
以上代碼將INI文件解析為配置信息,可以方便地訪問其中的數據。
七、Python解析HTML文件
通過Python的BeautifulSoup庫可以方便地解析HTML文件。以下為示例代碼:
from bs4 import BeautifulSoup with open('index.html', 'r') as f: html_str = f.read() soup = BeautifulSoup(html_str, 'html.parser') print(soup.find('h1').text)
以上代碼將HTML文件解析為樹形結構,並且可以通過訪問標籤和屬性來訪問其中的數據。
八、Python Word解析
Word是一種常用的文檔格式,通過Python的python-docx庫可以方便地進行解析。以下為示例代碼:
import docx doc = docx.Document('document.docx') for para in doc.paragraphs: print(para.text)
以上代碼將Word文檔解析為段落信息,並且可以方便地訪問其中的數據。
原創文章,作者:DHCG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/137006.html