首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python . ZipCode匹配

Python . ZipCode匹配
EN

Stack Overflow用户
提问于 2015-04-30 14:09:10
回答 1查看 1.8K关注 0票数 0

我正在使用Regex,而且我对使用python非常陌生。我无法让程序从文件中读取,并正确地检查匹配情况。我得到了一个跟踪错误,如下所示:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
3285
32816
32816-2362
32765-a234
32765-23
99999-9999

zipcode.py:

代码语言:javascript
运行
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-30 14:22:09

问题是readline()返回一个列表,并对类似于字符串的内容进行重新操作。这里有一种方法可以发挥作用:

代码语言:javascript
运行
复制
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。

编辑:

实际上,可以用一种更短、但不太清楚的方式来编写这篇文章:

代码语言:javascript
运行
复制
next((l for l in open('zipin.txt', 'r') if zip_re.match(l.strip())), None)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29970014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档