如何调整Python的get_records()函数加载MIT-BIH NSRDB等PhysioNet数据库?
Hey there! Let's figure out how to tweak that get_records() function in your mitdb.py to work with NSRDB and other PhysioNet databases. Here's a practical, flexible approach:
First, Make Sure You Have the Right Tooling
Most PhysioNet database interactions in Python rely on the wfdb library—if you don't have it installed yet, run:
pip install wfdb
Modify the get_records() Function for Universal Use
The original function was hardcoded for the MIT-BIH Arrhythmia Database. We'll refactor it to accept parameters that let you target any public PhysioNet database, including NSRDB. Here's the adjusted code:
import os import wfdb def get_records(database_name='mitdb', data_dir='datasets', records=None): """ Download and load records from any public PhysioNet database. Args: database_name (str): Name of the PhysioNet database (e.g., 'nsrdb' for Normal Sinus Rhythm Database) data_dir (str): Directory to store downloaded data (will be created if it doesn't exist) records (list, optional): Specific record IDs to download. If None, downloads all records in the database. Returns: list: List of loaded WFDB Record objects """ # Create the data directory if it doesn't exist os.makedirs(data_dir, exist_ok=True) # Get all record names if none are specified if records is None: record_names = wfdb.get_record_list(database_name) else: record_names = records # Download the requested records wfdb.dl_database( database=database_name, dl_dir=data_dir, records=record_names ) # Load each record into memory loaded_records = [] for record_name in record_names: record_path = os.path.join(data_dir, record_name) rec = wfdb.rdrecord(record_path) loaded_records.append(rec) return loaded_records
Key Changes Explained
- Parameter Flexibility: We added
database_name(defaults to 'mitdb' for backward compatibility) so you can switch to 'nsrdb', 'ptbdb', or any other public PhysioNet database. - Dynamic Record Lists: Instead of hardcoding record IDs, we use
wfdb.get_record_list(database_name)to fetch all records for the target database automatically. - Auto-Create Directories: The function now makes sure your
data_direxists, so you don't have to manually create folders. - Reusable Download Logic:
wfdb.dl_database()is PhysioNet's official method for downloading database files, so it works across all their public datasets.
How to Use It for NSRDB
To download and load the Normal Sinus Rhythm Database, just call the function like this:
nsrdb_records = get_records(database_name='nsrdb', data_dir='datasets/nsrdb')
Quick Notes
- For restricted PhysioNet databases (those requiring login), add
wfdb.set_auth("your_username", "your_password")before calling the function. - If you only need specific records from NSRDB, pass them as a list:
get_records('nsrdb', 'datasets/nsrdb', records=['16265', '16272'])
内容的提问来源于stack exchange,提问作者Ahmed K. Moustafa
相关产品推荐
相关产品推荐

