python搜索引擎代码
时间: 2023-07-23 21:04:22 浏览: 64
以下是一个简单的 Python 搜索引擎代码示例,它使用了 Python 的内置模块 `re` 和 `os`,以及第三方模块 `nltk`:
```python
import re
import os
from nltk.tokenize import word_tokenize
# 指定搜索目录
dir_path = "path/to/search/dir"
# 用户输入查询关键词
query = input("Enter your query: ")
# 将查询关键词分词
query_tokens = word_tokenize(query.lower())
# 遍历目录下所有文件
for filename in os.listdir(dir_path):
# 仅处理文本文件
if filename.endswith(".txt"):
file_path = os.path.join(dir_path, filename)
with open(file_path, "r", encoding="utf-8") as f:
text = f.read()
# 将文本内容分词
tokens = word_tokenize(text.lower())
# 匹配查询关键词
matches = [token for token in tokens if token in query_tokens]
# 如果有匹配项,则输出文件名和匹配项
if len(matches) > 0:
print(f"Matches found in {filename}: {matches}")
```
该代码将用户输入的查询关键词分词后,遍历指定目录下的所有文本文件,将文本内容也分词后,匹配查询关键词,并输出匹配项所在的文件名及匹配项。需要注意的是,该代码仅用于演示,实际应用中需要考虑更多因素,如文件编码、搜索速度等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)