在Python中进行模糊查询,通常有以下几种方法:
1. 使用正则表达式(`re`模块):
import re
匹配包含"apple"的所有字符串
pattern = re.compile("apple")
result = pattern.findall("I have an apple.")
print(result) 输出:['apple']
2. 使用`os`模块进行文件名模糊查询:
import os
模糊匹配进行搜索,文件名中包含“PRe”并且后缀是以“.zip”结尾
path = "F:/python_code"
files = os.listdir(path)
for f in files:
if "PRe" in f and f.endswith(".zip"):
print("found it!", f)
3. 使用第三方库`FuzzyWuzzy`进行模糊字符串匹配:
from fuzzywuzzy import process
choices = ["apple", "banana", "cherry", "date"]
user_input = "aple"
获取最匹配的结果
result = process.extractOne(user_input, choices)
print(result) 输出:('apple', 100)
4. 使用`fuzzyfinder`函数进行模糊文件名匹配:
from fuzzyfinder import fuzzyfinder
模糊匹配文件名
collection = ["django_migrations.py", "django_admin_log.py", "main_generator.py", "migrations.py", "api_user.doc", "user_group.doc", "accounts.txt"]
user_input = "djm"
suggestions = fuzzyfinder(user_input, collection)
print(suggestions) 输出:['django_migrations.py', 'django_admin_log.py']
以上方法可以帮助你在Python中实现模糊查询