本文目录导读:

基础Python脚本(使用列表)
# 简单的诗词数据库
poems = [
{"title": "静夜思", "author": "李白", "content": "床前明月光,疑是地上霜,举头望明月,低头思故乡。"},
{"title": "春晓", "author": "孟浩然", "content": "春眠不觉晓,处处闻啼鸟,夜来风雨声,花落知多少。"},
{"title": "登鹳雀楼", "author": "王之涣", "content": "白日依山尽,黄河入海流,欲穷千里目,更上一层楼。"}
]
def search_poems(keyword):
results = []
for poem in poems:
if keyword in poem["title"] or keyword in poem["content"] or keyword in poem["author"]:
results.append(poem)
return results
# 使用示例
keyword = "月"
results = search_poems(keyword)
for r in results:
print(f"{r['title']} - {r['author']}")
print(r['content'])
print("---")
使用JSON文件的完整检索系统
import json
import re
class PoemSearch:
def __init__(self, json_file="poems.json"):
self.poems = self.load_poems(json_file)
def load_poems(self, file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
def search_by_keyword(self, keyword, fields=None):
"""
关键词检索
:param keyword: 搜索关键词
:param fields: 搜索范围,如 ["title", "content", "author"]
"""
if fields is None:
fields = ["title", "content", "author", "dynasty"]
results = []
keyword_lower = keyword.lower()
for poem in self.poems:
for field in fields:
if field in poem and isinstance(poem[field], str):
if keyword_lower in poem[field].lower():
results.append(poem)
break
return results
def search_by_regex(self, pattern, fields=None):
"""
正则表达式检索
"""
if fields is None:
fields = ["title", "content"]
results = []
for poem in self.poems:
for field in fields:
if field in poem:
if re.search(pattern, poem[field]):
results.append(poem)
break
return results
def fuzzy_search(self, keyword, threshold=0.6):
"""
模糊检索(使用Levenshtein距离)
"""
from fuzzywuzzy import fuzz
results = []
for poem in self.poems:
score = 0
# 计算标题和内容的相似度
title_score = fuzz.partial_ratio(keyword, poem.get("title", ""))
content_score = fuzz.partial_ratio(keyword, poem.get("content", ""))
score = max(title_score, content_score) / 100
if score >= threshold:
poem["similarity"] = score
results.append(poem)
# 按相似度排序
results.sort(key=lambda x: x["similarity"], reverse=True)
return results
# 使用示例
search = PoemSearch()
# 普通搜索
results = search.search_by_keyword("明月")
# 正则搜索 - 搜索以"月"结尾的诗句
results = search.search_by_regex(r'月$')
# 模糊搜索
results = search.fuzzy_search("明朋光")
命令行版本
#!/usr/bin/env python3
# poem_search.py
import json
import sys
from colorama import init, Fore, Style
init(autoreset=True) # 初始化colorama
class PoemCLI:
def __init__(self):
self.poems = self.load_default_data()
def load_default_data(self):
# 这里可以加载JSON文件
return [
{
"title": "静夜思",
"author": "李白",
"dynasty": "唐",
"content": "床前明月光,疑是地上霜,举头望明月,低头思故乡。"
},
# ... 更多诗词
]
def search_and_display(self, keyword):
results = []
for poem in self.poems:
if (keyword in poem["title"] or
keyword in poem["content"] or
keyword in poem["author"]):
results.append(poem)
if not results:
print(f"{Fore.RED}未找到包含'{keyword}'的诗词")
return
print(f"{Fore.GREEN}找到 {len(results)} 首诗词:\n")
for i, poem in enumerate(results, 1):
print(f"{Fore.YELLOW}{i}. {poem['title']}")
print(f" {Fore.CYAN}作者:{poem['author']} | 朝代:{poem['dynasty']}")
print(f" {Fore.WHITE}{poem['content']}")
# 高亮关键字
highlighted = poem['content'].replace(
keyword,
f"{Fore.RED}{keyword}{Style.RESET_ALL}"
)
print(f" {highlighted}")
print()
def main():
if len(sys.argv) < 2:
print("使用方法:python poem_search.py <关键词>")
sys.exit(1)
keyword = sys.argv[1]
cli = PoemCLI()
cli.search_and_display(keyword)
if __name__ == "__main__":
main()
使用SQLite数据库的高级版本
import sqlite3
import jieba
class AdvancedPoemSearch:
def __init__(self, db_path="poems.db"):
self.conn = sqlite3.connect(db_path)
self.create_tables()
def create_tables(self):
cursor = self.conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS poems (
id INTEGER PRIMARY KEY,
title TEXT,
author TEXT,
dynasty TEXT,
content TEXT
)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_content
ON poems(content)
''')
self.conn.commit()
def fulltext_search(self, keyword):
"""全文搜索"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT * FROM poems
WHERE content LIKE ? OR title LIKE ? OR author LIKE ?
''', (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%'))
return cursor.fetchall()
def keyword_analysis(self, text):
"""中文分词和关键词提取"""
words = jieba.lcut(text)
# 去除停用词
stop_words = set(['的', '了', '是', '在', '我', '有', '和', '就', '不', '人'])
keywords = [w for w in words if w not in stop_words and len(w) > 1]
return keywords
def advanced_search(self, keywords):
"""多关键词组合搜索"""
results = []
keywords_list = keywords.split()
for poem in self.get_all_poems():
score = 0
for kw in keywords_list:
if kw in poem['content']:
score += 1
if kw in poem['title']:
score += 2 # 标题匹配权重更高
if score > 0:
poem['score'] = score
results.append(poem)
# 按相关性排序
results.sort(key=lambda x: x['score'], reverse=True)
return results
# 使用示例
searcher = AdvancedPoemSearch()
results = searcher.fulltext_search("明月")
results = searcher.advanced_search("明月 思乡") # 多关键词搜索
PHP版本(Web接口)
<?php
// poem_search.php
class PoemSearch {
private $poems = [];
public function __construct() {
$this->loadPoems();
}
private function loadPoems() {
// 从文件加载诗词数据
$json = file_get_contents('poems.json');
$this->poems = json_decode($json, true);
}
public function search($keyword, $fields = ['title', 'content', 'author']) {
$results = [];
foreach ($this->poems as $poem) {
foreach ($fields as $field) {
if (isset($poem[$field]) &&
mb_stripos($poem[$field], $keyword) !== false) {
$results[] = $poem;
break;
}
}
}
return $results;
}
public function ajaxResponse($keyword) {
header('Content-Type: application/json; charset=utf-8');
$results = $this->search($keyword);
echo json_encode([
'status' => 'success',
'count' => count($results),
'data' => $results
]);
}
}
// HTML前端界面
?>
<!DOCTYPE html>
<html>
<head>诗词检索</title>
<style>
.search-box { margin: 20px; }
.result-item {
border: 1px solid #ddd;
margin: 10px 0;
padding: 10px;
}
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<div class="search-box">
<input type="text" id="keyword" placeholder="输入关键词">
<button onclick="searchPoems()">搜索</button>
</div>
<div id="results"></div>
<script>
function searchPoems() {
const keyword = document.getElementById('keyword').value;
fetch(`poem_search.php?keyword=${encodeURIComponent(keyword)}`)
.then(response => response.json())
.then(data => {
displayResults(data);
});
}
function displayResults(data) {
const container = document.getElementById('results');
container.innerHTML = `<h3>找到 ${data.count} 首诗词</h3>`;
data.data.forEach(poem => {
const div = document.createElement('div');
div.className = 'result-item';
div.innerHTML = `
<h4>${poem.title}</h4>
<p>作者:${poem.author} | 朝代:${poem.dynasty}</p>
<p>${highlightKeyword(poem.content, keyword)}</p>
`;
container.appendChild(div);
});
}
function highlightKeyword(text, keyword) {
const regex = new RegExp(keyword, 'gi');
return text.replace(regex, `<span class="highlight">$&</span>`);
}
</script>
</body>
</html>
使用建议
- 小规模数据:使用Python列表或JSON文件
- 大规模数据:使用数据库(SQLite、MySQL)
- 需要高性能:使用Elasticsearch或Whoosh
- Web应用:使用PHP/Node.js配合前端框架
- 需要考虑:
- 中文分词(jieba)
- 同义词扩展
- 拼音搜索
- 模糊匹配
这些脚本可以根据你的具体需求进行调整和扩展,需要我详细解释某个特定部分吗?
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播