0

我的代码有问题。我编写了一个用于提取参数的函数,通过发送原始字符串、前/后文本片段以及文本中的出现次数。当我用简单的代码编写它时,效果很好:

searchstr = 'qwer1234asdfqwer5678asdfqwer1234asdfqwer5678asdf'
startstr = 'qwer'
endstr = 'asdf'
occurancenr = 4
start = searchstr.find(startstr)
print 'start = ' + str(start)
while start >= 0 and occurancenr > 1:
  start = searchstr.find(startstr, start + len(startstr))
  occurancenr -= 1
  print 'start = ' + str(start) + ', and nr = ' + str(occurancenr)
start = start + len(startstr)
end = searchstr.index( endstr, start )
print 'result = ' + searchstr[start:end]

但是当我把它放在返回字符串的方法中时,我得到了错误:

继承人的功能:

  def findparam (self, searchstr, startstr, endstr, occurancenr):
  start = searchstr.find(startstr)
  while start >= 0 and occurancenr > 1:
    start = searchstr.find(startstr, start + len(startstr))
    occurancenr -= 1
  start = start + len(startstr)
  end = searchstr.index( endstr, start )
  return 'result = ' + searchstr[start:end]

这是它的呼吁:

abc = 'qwer1234asdfqwer5678asdf'
aa = 'qwer'
bb = 'asdf'
print self.findparam(abc, aa, bb, 1)

错误如下所示:

SyntaxError: ('invalid syntax', ('C:\\grinder-3.4\\scripts\\ResultCheckMerged.py', 367, 3, '  start = searchstr.find(startstr)'))
(no code object) at line 0

从技术上讲,这是一个运行磨床脚本的函数,比较器使用 jython,但是,由于没有使用 java 代码并且它只是 python 代码,我认为这是一个 python 问题。但是,也许它与此有关。

对此表示赞赏的任何提示!

4

2 回答 2

2

你只需要正确缩进你的代码。下一个应该工作:

  def findparam (self, searchstr, startstr, endstr, occurancenr):
    start = searchstr.find(startstr)
    while start >= 0 and occurancenr > 1:
      ...
于 2012-01-18T10:17:13.490 回答
0

不要缩进 def 行。


def findparam (self, searchstr, startstr, endstr, occurancenr):
      start = searchstr.find(startstr)
      while start >= 0 and occurancenr > 1:
        start = searchstr.find(startstr, start + len(startstr))
        occurancenr -= 1
      start = start + len(startstr)
      end = searchstr.index( endstr, start )
      return 'result = ' + searchstr[start:end]
于 2012-01-18T11:34:56.420 回答