类型错误:不可散列的类型"list",当我尝试使用正则表达式查找和计算文本文件中单个单词的重复次数时



我正在解决一个问题,我使用 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,可用作字典键。

最新更新