搜索引擎代码 python
时间: 2023-11-12 09:43:26 浏览: 33
你可以使用 Python 编写一个简单的搜索引擎代码,以下是一个基本的示例:
```python
# 假设有一个包含网页内容的字典
web_pages = {
"1": "This is the content of page 1",
"2": "Here is the content of page 2",
"3": "Page 3 has some interesting content",
"4": "The content of page 4 is different",
"5": "This is a sample content for page 5"
}
def search(query):
results = []
for page_id, content in web_pages.items():
if query in content:
results.append(page_id)
if results:
print("Search results for '{}':".format(query))
for page_id in results:
print("- Page {}: {}".format(page_id, web_pages[page_id]))
else:
print("No results found for '{}'. Try a different query.".format(query))
# 测试搜索功能
search("content")
```
这个示例代码定义了一个 `search` 函数,它接受一个查询字符串作为参数,并在 `web_pages` 字典中搜索包含该查询字符串的网页内容。如果找到匹配的结果,它会打印出相关的网页内容。如果没有找到匹配的结果,它会给出相应的提示。
当然,这只是一个简单的示例,实际的搜索引擎功能要更加复杂和庞大。这个示例可以帮助你理解搜索引擎的基本原理和实现方式。你可以根据实际需求对代码进行扩展和改进。