使用正则表达式时获取TypeError

问题描述 投票:-1回答:1

使用下面的代码,我不断收到错误。我有一个非常相似的示例代码,但这个代码似乎不起作用。此外,我确实通过regex101.com运行我的正则表达式,所以它应该工作。

Traceback (most recent call last):
  File "/Users/name/Assignment 3.py", line 8, in <module>
    print(re.match(pattern, file1))
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or buffer    

码:

import os
import re
import csv

pattern = "^[A-Za-z]*[,]$"
file1 = open("10000DirtyNames.csv", "r")

print(re.match(pattern, file1))

if (re.match(pattern, file1)) != None:
    print("Match")
else:
    print("Does not match")

file1.close()
python regex traceback
1个回答
1
投票

我猜你真正想要的是查看文件的内容:

with open("10000DirtyNames.csv", "r") as file1:
    if (re.search(pattern, file1.read()):
        print("Match")
    else:
        print("Does not match")

另外,re.search()re.match()之间存在差异,后者仅在字符串的开头起作用(因此,锚点被隐式设置)。 最后检查None可以通过is not None或简单地用if x:完成

© www.soinside.com 2019 - 2024. All rights reserved.