在Python中,模糊匹配文件可以通过多种方法实现,以下是几种常见的方法:
1. 使用`os`模块和`endswith`方法:
import ospath = "C:/www/html/"files = os.listdir(path)for f in files:if 'test' in f and f.endswith('.txt'):print(f)
2. 使用`glob`模块进行模糊匹配:
import glob匹配所有以 .py 结尾的文件files = glob.glob('*.py')匹配所有以 test 开头的文件files = glob.glob('test*')
3. 使用`re`模块进行正则表达式模糊匹配:
import reteststr = "你好,hello,world"pattern1 = "llo"r1 = re.search(pattern1, teststr)if r1:print(pattern1, "匹配成功.")else:print(pattern1, "匹配失败.")

4. 使用`fuzzywuzzy`库进行模糊匹配:
from fuzzywuzzy import fuzz简单的匹配(Ratio)print(fuzz.ratio("test is fuzzywuzzy", "test is fuzzywuzzy"))部分匹配(Partial Ratio)print(fuzz.partial_ratio("test is fuzzywuzzy", "test is fuzzywuzzy.."))标记排序匹配(Token Sort Ratio)print(fuzz.token_sort_ratio("test is fuzzywuzzy", "test is fuzzywuzzy"))标记集合匹配(Token Set Ratio)print(fuzz.token_set_ratio("test is fuzzywuzzy", "test is fuzzywuzzy"))
5. 使用`time`模块查找最后修改时间为1小时内的文件:
import osimport timedef transTime(file_time):now = time.time()deltaH = 3600 1小时f = time.localtime(file_time)if f > (now - deltaH):return Trueelse:return Falsedef find_file(dir, name):pass_name = []for i in os.listdir(dir):if os.path.isfile(os.path.join(dir, i)):if name in os.path.splitext(i):check_file = os.path.join(dir, i)if transTime(check_file):pass_name.append(i)return pass_name
以上方法可以帮助你根据不同的需求进行文件名的模糊匹配。请选择适合你需求的方法进行尝试
