Python 3.8正则搜索时触发TypeError: unhashable type: 'list'求助
问题原因
根本不是冒号的问题,是构建搜索模式列表时的结构错误:dvc_ptrns = [ptrn_print, ptrn_wlsap] 里的 ptrn_wlsap本身就是一个列表,导致dvc_ptrns变成了嵌套列表(结构为['2022:28', ['2022:34e','2022:34f']])。当循环到这个子列表时,re.search试图把列表当作正则模式传入,但正则要求第一个参数必须是字符串,且Python正则的缓存机制需要参数是可哈希类型(列表不可哈希),因此抛出TypeError: unhashable type: 'list'。
解决方法
把嵌套列表扁平化,让dvc_ptrns变成所有字符串模式的一维列表即可,最简单的方式是用列表拼接:
修改这一行代码:
dvc_ptrns = [ptrn_print] + ptrn_wlsap
修改后dvc_ptrns的结构为['2022:28', '2022:34e', '2022:34f'],每个元素都是字符串,re.search就能正常处理。
补充说明:正则表达式里的冒号不是特殊元字符,完全不需要转义,你之前的方向判断错误。
修正后的完整代码
import re from datetime import datetime def count_matching_lines(filename, dvc_ptrns): count = 0 with open(filename, 'r') as file: for line in file: for pattern in dvc_ptrns: if re.search(pattern, line): count += 1 print(count) break # 可选:若一行匹配多个模式仅计数一次,保留此break;否则删除 return count ## Define paths devpath = f'/home/user' rootpath = devpath # Get current date for logging current_date = datetime.now().strftime('%Y%m%d') # File paths filtered_file = f'{rootpath}/filtered{current_date}.csv' filename = filtered_file # Replace with your file ptrn_print = '2022:28' ptrn_wlsap = ['2022:34e','2022:34f'] dvc_ptrns = [ptrn_print] + ptrn_wlsap # 此处为修改部分 count = count_matching_lines(filename, dvc_ptrns) print("Number of matching lines:", count)
内容的提问来源于stack exchange,提问作者Ippy
相关产品推荐
相关产品推荐

