我正在使用Regex,而且我对使用python非常陌生。我无法让程序从文件中读取,并正确地检查匹配情况。我得到了一个跟踪错误,如下所示:
Traceback (most recent call last):
    File "C:\Users\Systematic\workspace\Project8\src\zipcode.py", line 18, in <module>
      m = re.match(info, pattern)
    File "C:\Python34\lib\re.py", line 160, in match
      return _compile(pattern, flags).match(string)
    File "C:\Python34\lib\re.py", line 282, in _compile
      p, loc = _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'zipin.txt:
3285
32816
32816-2362
32765-a234
32765-23
99999-9999zipcode.py:
from pip._vendor.distlib.compat import raw_input
import re
userinput = raw_input('Please enter the name of the file containing the input zipcodes: ')
myfile = open(userinput)
info = myfile.readlines()
pattern = '^[0-9]{5}(?:-[0-9]{4})?$'
m = re.match(info, pattern)
if m is not None:
    print("Match found - valid U.S. zipcode: " , info, "\n")
else: print("Error - no match - invalid U.S. zipcode: ", info, "\n")
myfile.close()发布于 2015-04-30 14:22:09
问题是readline()返回一个列表,并对类似于字符串的内容进行重新操作。这里有一种方法可以发挥作用:
import re
zip_re = re.compile('^[0-9]{5}(?:-[0-9]{4})?$')
for l in open('zipin.txt', 'r'):
    m = zip_re.match(l.strip())
    if m:
        print l
        break
if m is None:
    print("Error - no match")代码现在在文件行的循环中运行,并试图在每一行的剥离版本上匹配re。
编辑:
实际上,可以用一种更短、但不太清楚的方式来编写这篇文章:
next((l for l in open('zipin.txt', 'r') if zip_re.match(l.strip())), None)https://stackoverflow.com/questions/29970014
复制相似问题