这应该验证一行中有一个IP,然后打印该行,但我正在接收
TypeError: unsupported operand types for 'list' & 'int'
我想不出我现有代码的解决方案,有人可以帮忙吗?
import sys
import re
match = 0
def CheckIP(ip, filter):
match = re.compile(b"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", ip)
if match == None:
print ("No IP's in this file!")
sys.exit(0)
else:
pass
with open('text.log') as f:
x=[]
count = 0
for l in f:
x = l.strip().split("\t")[5:8] # Grab the elements you want...
x.pop(1) #... but remove the element you don't
CheckIP(x, match)
print(" ".join(x)) # Now print them
print('\n')
count += 1
if count == 20:
print("\n\n\n\n\n-----NEW GROUPING OF 20 RESULTS-----\n\n\n\n\n\n")
count = 0
print(count)
修改:
import sys
import re
with open('text.log') as f:
x=[]
count = 0
for l in f:
x = l.strip().split("\t")[5:8] # Grab the elements you want...
x.pop(1) #... but remove the element you don't
match = re.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", x)
if any(lambda s: match.search(s) for s in x):
pass
else:
print ("No IP's in this file!")
sys.exit(0)
print(" ".join(x)) # Now print them
print('\n')
count += 1
if count == 20:
print("\n\n\n\n\n-----NEW GROUPING OF 20 RESULTS-----\n\n\n\n\n\n")
count = 0
print(count)
错误:
Traceback (most recent call last):
File "D:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 76, in exec_file
exec(code_obj, global_variables)
File "C:\Users\marco\Documents\Visual Studio 2013\Projects\PythonApplication4\
PythonApplication4\a2.py", line 10, in <module>match = re.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", x)
File "D:\Python34\lib\re.py", line 219, in compile
return _compile(pattern, flags)
File "D:\Python34\lib\re.py", line 275, in _compile
bypass_cache = flags & DEBUG
TypeError: unsupported operand type(s) for &: 'list' and 'int'
Press any key to continue . . .
答案 0 :(得分:8)
您未正确使用re.compile
。第二个参数应该是由按位“或”re
个标志组成的整数,而不是要匹配的字符串列表。
执行您尝试执行的操作的最简单方法是:
pattern = re.compile( ### regex ### )
if any(pattern.search(s) for s in ip):
pass
else:
print ("No IP's in this file!")
sys.exit(0)