Type error : unhashable type "list" , when am trying to use regex to find and count number of repetion of single word in text file

Type error : unhashable type "list" , when am trying to use regex to find and count number of repetion of single word in text file

我正在解决使用 python 打开文件句柄并让用户手动输入正则表达式命令的问题

print("\t ***hello user*** ")
# simulate the operation of 'grep' on linux using python ask
# the user to enter regular expression and count the numbers 
# of lines that matched the regex

# first and most imp import module define variable
import re

di = {}

infile = input("Enter the file name: ")

regin = input("input regex command")


#pre defining file for help debug
if len(infile) < 1 : infile = 'mbox-short.txt'

# checking error if file present or not

try:
    fhand = open(infile)
except:
    # exit if file not present 
    print("Invalid entery")
    quit()


for line in fhand:
    
    #strip \n character from line using strip function
    line = line.strip()
    for w in line:
        w = re.findall(regin,line)
        di[w] = di.get(w,0) + 1
print(di)

**代码的逻辑是要求用户输入文件和正则表达式,然后打开文件在文件中找到与正则表达式匹配的单词并计算该单词出现的行数**

enter code here = output
r3tr0@iCBM:~/Desktop/py/python/regex$ python3 ex1.py 
         ***hello user*** 
Enter the file name: 
input regex command^Author
Traceback (most recent call last):
  File "ex1.py", line 33, in <module>
    di[w] = di.get(w,0) + 1
TypeError: unhashable type: 'list'

我不确定下一步该做什么

for line in fhand:
    
    #strip \n character from line using strip function
    line = line.strip()
    for w in line:

        w = tuple(re.findall(regin,line))

        di[w] = di.get(w,0) + 1
print(di)

re.findall(regin, line) 必须返回 list 并且您不能使用 list 作为字典的键。因此,将 list 转换为 tuple,它可以用作字典键。