Python案例如何实现精准查询?

wen python案例 26

本文目录导读:

Python案例如何实现精准查询?

  1. 基础精准查询(精确匹配)
  2. 数据库精准查询
  3. 文件内容精准查询
  4. 带索引优化的精准查询
  5. 模糊匹配与严格精准查询结合
  6. 综合示例:图书管理系统精准查询
  7. 性能对比和最佳实践
  8. 精准查询的最佳实践建议

我来详细介绍Python实现精准查询的几种常用方法,并附上完整的示例代码。

基础精准查询(精确匹配)

# 示例1:列表精准查询
def exact_search_list(data, target):
    """在列表中精准查找元素"""
    try:
        index = data.index(target)
        return f"找到元素 '{target}',索引位置:{index}"
    except ValueError:
        return f"未找到元素 '{target}'"
# 使用示例
my_list = ['apple', 'banana', 'orange', 'grape']
print(exact_search_list(my_list, 'banana'))  # 找到
print(exact_search_list(my_list, 'watermelon'))  # 未找到
# 示例2:字典精准查询
def exact_search_dict(data, key):
    """在字典中精准查找键"""
    if key in data:
        return f"找到键 '{key}',对应的值:{data[key]}"
    else:
        return f"未找到键 '{key}'"
# 使用示例
my_dict = {'name': '张三', 'age': 25, 'city': '北京'}
print(exact_search_dict(my_dict, 'name'))
print(exact_search_dict(my_dict, 'gender'))

数据库精准查询

import sqlite3
class DatabaseSearch:
    def __init__(self, db_name='example.db'):
        self.conn = sqlite3.connect(db_name)
        self.cursor = self.conn.cursor()
        self.create_table()
    def create_table(self):
        """创建示例表"""
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT UNIQUE,
                age INTEGER
            )
        ''')
        # 插入示例数据
        sample_data = [
            (1, '张三', 'zhangsan@example.com', 25),
            (2, '李四', 'lisi@example.com', 30),
            (3, '王五', 'wangwu@example.com', 28)
        ]
        self.cursor.executemany('INSERT OR IGNORE INTO users VALUES (?,?,?,?)', sample_data)
        self.conn.commit()
    def exact_search_by_name(self, name):
        """按姓名精准查询"""
        sql = "SELECT * FROM users WHERE name = ?"
        self.cursor.execute(sql, (name,))
        result = self.cursor.fetchone()
        return result if result else f"未找到姓名为 '{name}' 的用户"
    def exact_search_by_email(self, email):
        """按邮箱精准查询"""
        sql = "SELECT * FROM users WHERE email = ?"
        self.cursor.execute(sql, (email,))
        result = self.cursor.fetchone()
        return result if result else f"未找到邮箱为 '{email}' 的用户"
    def close(self):
        self.conn.close()
# 使用示例
db = DatabaseSearch()
print(db.exact_search_by_name('张三'))
print(db.exact_search_by_email('lisi@example.com'))
db.close()

精准查询

import json
import csv
class FileSearch:
    @staticmethod
    def search_json_exact(file_path, key, value):
        """在JSON文件中精准查询"""
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        results = []
        for item in data:
            if item.get(key) == value:
                results.append(item)
        return results if results else f"未找到 '{key}={value}' 的匹配项"
    @staticmethod
    def search_csv_exact(file_path, column_index, value):
        """在CSV文件中精准查询"""
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            header = next(reader)  # 跳过表头
            results = []
            for row in reader:
                if len(row) > column_index and row[column_index] == value:
                    results.append(row)
            return results if results else f"未找到匹配项"
# 创建示例JSON文件
sample_data = [
    {"id": 1, "name": "产品A", "price": 100},
    {"id": 2, "name": "产品B", "price": 200},
    {"id": 3, "name": "产品C", "price": 100}
]
with open('products.json', 'w', encoding='utf-8') as f:
    json.dump(sample_data, f, ensure_ascii=False)
# 使用示例
file_search = FileSearch()
results = file_search.search_json_exact('products.json', 'price', 100)
print(f"价格100的产品:{results}")

带索引优化的精准查询

class IndexedSearch:
    def __init__(self):
        self.data = []
        self.index = {}  # 索引字典
    def add_data(self, items, key_field):
        """添加数据并建立索引"""
        for item in items:
            self.data.append(item)
            key = item[key_field]
            if key not in self.index:
                self.index[key] = []
            self.index[key].append(len(self.data) - 1)
    def exact_search_with_index(self, key):
        """使用索引进行精准查询"""
        if key in self.index:
            indices = self.index[key]
            return [self.data[i] for i in indices]
        else:
            return f"未找到键 '{key}'"
    def exact_search_without_index(self, key_field, value):
        """不使用索引的线性搜索(对比)"""
        results = []
        for item in self.data:
            if item[key_field] == value:
                results.append(item)
        return results if results else "未找到匹配项"
# 使用示例
searcher = IndexedSearch()
# 添加大量数据
dataset = [
    {"id": i, "name": f"用户{i}", "age": 20 + (i % 30)}
    for i in range(1, 10001)
]
# 按名称索引
searcher.add_data(dataset, "name")
# 精准查询
result_index = searcher.exact_search_with_index("用户5000")
result_linear = searcher.exact_search_without_index("name", "用户5000")
print(f"索引查询结果:{result_index}")
print(f"线性查询结果:{result_linear}")

模糊匹配与严格精准查询结合

import re
class AdvancedSearch:
    @staticmethod
    def strict_exact_search(text, keyword):
        """严格精准匹配(完全相等)"""
        return text == keyword
    @staticmethod
    def word_exact_search(text, keyword):
        """单词精准匹配(考虑单词边界)"""
        pattern = r'\b' + re.escape(keyword) + r'\b'
        return bool(re.search(pattern, text))
    @staticmethod
    def case_sensitive_search(text, keyword):
        """大小写敏感精准匹配"""
        return keyword in text
    @staticmethod
    def case_insensitive_search(text, keyword):
        """大小写不敏感精准匹配"""
        return keyword.lower() in text.lower()
    @staticmethod
    def search_in_list(data, keyword, exact=True):
        """在列表中执行不同类型的精准查询"""
        if exact:
            # 完全精准匹配
            return [item for item in data if item == keyword]
        else:
            # 包含匹配(但要求精准包含)
            return [item for item in data if keyword in str(item)]
# 使用示例
text = "Python是一种优秀的编程语言"
searcher = AdvancedSearch()
print(searcher.strict_exact_search(text, "Python"))  # False(文本不完全等于"Python")
print(searcher.word_exact_search(text, "Python"))   # True("Python"作为一个单词存在)
print(searcher.case_sensitive_search(text, "python"))  # False(大小写不匹配)
print(searcher.case_insensitive_search(text, "python"))  # True(忽略大小写)

综合示例:图书管理系统精准查询

class BookSearchSystem:
    def __init__(self):
        self.books = []
        self.isbn_index = {}  # ISBN索引
        self.title_index = {}  # 书名索引
    def add_book(self, book):
        """添加图书并建立索引"""
        self.books.append(book)
        isbn = book['isbn']
        title = book['title']
        # ISBN索引(精准匹配)
        self.isbn_index[isbn] = len(self.books) - 1
        # 书名索引(首字母,用于快速定位)
        first_char = title[0] if title else ''
        if first_char not in self.title_index:
            self.title_index[first_char] = []
        self.title_index[first_char].append(len(self.books) - 1)
    def search_by_isbn(self, isbn):
        """按ISBN精准查询"""
        if isbn in self.isbn_index:
            index = self.isbn_index[isbn]
            return self.books[index]
        return f"未找到ISBN为 '{isbn}' 的图书"
    def search_by_title_exact(self, title):
        """按书名精准查询"""
        results = []
        first_char = title[0] if title else ''
        if first_char in self.title_index:
            for index in self.title_index[first_char]:
                if self.books[index]['title'] == title:
                    results.append(self.books[index])
        return results if results else f"未找到书名为 '{title}' 的图书"
    def search_by_author_and_year(self, author, year):
        """按作者和年份精准查询"""
        results = []
        for book in self.books:
            if (book['author'] == author and 
                book['year'] == year):
                results.append(book)
        return results if results else f"未找到作者为'{author}'、年份为{year}的图书"
# 使用示例
book_system = BookSearchSystem()
# 添加示例图书
books_data = [
    {"isbn": "978-7-111-54760-4", "title": "Python编程", "author": "张三", "year": 2023},
    {"isbn": "978-7-111-54760-5", "title": "Java编程", "author": "李四", "year": 2022},
    {"isbn": "978-7-111-54760-6", "title": "Python高级编程", "author": "张三", "year": 2023}
]
for book in books_data:
    book_system.add_book(book)
# 执行精准查询
print(book_system.search_by_isbn("978-7-111-54760-4"))
print(book_system.search_by_title_exact("Python编程"))
print(book_system.search_by_author_and_year("张三", 2023))

性能对比和最佳实践

import time
import random
def performance_comparison():
    """对比不同查询方法的性能"""
    # 生成测试数据
    data_size = 100000
    test_data = [f"item_{i}" for i in range(data_size)]
    # 创建索引
    index = {item: i for i, item in enumerate(test_data)}
    # 测试查询
    search_items = ["item_0", "item_50000", "item_99999", "not_exist"]
    for item in search_items:
        print(f"\n查询 '{item}':")
        # 1. 列表线性搜索
        start = time.time()
        result = item in test_data
        linear_time = time.time() - start
        print(f"  线性搜索: {linear_time:.6f}秒")
        # 2. 字典索引搜索
        start = time.time()
        result = item in index
        index_time = time.time() - start
        print(f"  索引搜索: {index_time:.6f}秒")
        # 3. set搜索
        start = time.time()
        test_set = set(test_data)
        result = item in test_set
        set_time = time.time() - start
        print(f"  Set搜索: {set_time:.6f}秒")
# 运行性能对比
performance_comparison()

精准查询的最佳实践建议

  1. 使用合适的数据结构:对于频繁查询,考虑使用字典或集合
  2. 建立索引:大数据集时建立索引可以大幅提升性能
  3. 注意边界情况:处理空值、特殊字符、编码问题
  4. 考虑使用数据库:复杂查询需求时使用数据库管理系统
  5. 缓存查询结果:对于重复查询,考虑缓存结果
  6. 注意内存使用:索引会消耗额外内存,需要权衡

这些示例涵盖了Python实现精准查询的多种场景,你可以根据实际需求选择合适的方法。

抱歉,评论功能暂时关闭!