使用下面的代码,我不断收到错误。我有一个非常相似的示例代码,但这个代码似乎不起作用。此外,我确实通过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()
我猜你真正想要的是查看文件的内容:
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:
完成