-1

我正在尝试转换这个 php 函数

function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);

    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}

我已经编写了这个 python 函数,但没有按预期工作。

def strposR(haystack, needle):
    if strlen(needle) > strlen(haystack):
        sys.stderr.write("length of argument 2 must be <= argument 1")
    seeks = []
    seek = 0
    while seek == haystack.rfind(needle):
        seeks.append(seek)
        haystack = haystack[0:seek]
    return seeks
def strlen(x):
    return len(x)

我做错了什么?任何指针将不胜感激。

4

3 回答 3

3

警告

  1. strrpos并且string.rfind当针无法定位时不会返回相同的值。在 php中strrpos返回false,但 python 的string.rfind返回-1

  2. php 版本中的while-conditional不使用严格比较,因此如果在结果数组中找到针头,该函数不会将偏移量存储0在结果数组中,要解决此问题,代码应编写为:

    while (($seek = strrpos ($haystack, $needle)) !== false)


你问题的根源..

while($seek = strrpos($haystack, $needle)) # PHP
while seek == haystack.rfind(needle):      # python

上面两行没有提供等价的功能,php-condition等价写成:

while (($seek = strrpos ($haystack, $needle)) != false) 

我会将您的 python 循环更改为:

while True:
  seek = haystack.rfind(needle)
 
  if seek == -1:
    break

  if seek ==  0: # because of mentioned bug in the php version
    break

  seeks.append(seek)
  haystack = haystack[0:seek]
于 2012-07-15T23:48:44.750 回答
1

一些小改动:

def strposR(haystack, needle):
    if len(needle) > len(haystack):
        sys.stderr.write("length of argument 2 must be <= argument 1")
    seeks = []
    seek = haystack.rfind(needle)
    while seek != -1:
        seeks.append(seek)
        haystack = haystack[0:seek]
        seek = haystack.rfind(needle)
    return seeks
于 2012-07-15T23:45:46.920 回答
1

这对我有用:

def strpos_r(haystack, needle):
    positions = []
    position = haystack.rfind(needle)

    while position != -1:
        positions.append(position)
        haystack = haystack[:position]
        position = haystack.rfind(needle)

    return positions

此外,函数不应真正为您处理输入错误。您通常只是return False或让函数抛出执行错误。

于 2012-07-15T23:47:18.477 回答