2016-07-15 171 views
0

我想做一个模式搜索,如果匹配,然后设置计数器值bitarray。python正则表达式错误

runOutput = device[router].execute (cmd) 
      runOutput = output.split('\n') 
      print(runOutput) 
      for this_line,counter in enumerate(runOutput): 
       print(counter) 
       if re.search(r'dev_router', this_line) : 
        #want to use the counter to set something 

得到以下错误:

if re.search(r'dev_router', this_line) :

2016-07-15T16:27:13: %ERROR: File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166,

in search 2016-07-15T16:27:13: %-ERROR: return _compile(pattern, flags).search(string)

2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer

回答

2

你混了论据enumerate() - 首先进入指数,则项目本身。替换:

for this_line,counter in enumerate(runOutput): 

有:

for counter, this_line in enumerate(runOutput): 

你在这种情况下获得一个TypeError因为this_line是一个整数,re.search()需要一个字符串作为第二个参数。为了证明:

>>> import re 
>>> 
>>> this_line = 0 
>>> re.search(r'dev_router', this_line) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search 
    return _compile(pattern, flags).search(string) 
TypeError: expected string or buffer 

顺便说一句,像PyCharm现代IDE可以静态检测这样的问题:

enter image description here

(Python的3.5用于此截图)

+0

然后计数器可以是这样简单的:在循环'counter = 0'之前,并且如果匹配'counter + = 1' –