1

我必须将两个 Python 函数翻译成 PHP。第一个是:

def listspaces(string):
        return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]

我假设这将检查提供的字符串中的空间并在找到第一次出现空间时返回 True,这是正确的吗?

这是什么i-1?是-1吗?

在 PHP 中,我们使用[]数组。这里我们[]使用返回,这个函数会返回 true 还是 false 或空格位置数组?

第二个功能是

def trimcopy(copy, spaces, length=350):

    try:
        if len(copy) < length:
            return copy
        else:
            loc = 0
            for space in spaces:
                if space < length:
                    loc = space
                else:
                    return copy[:loc]
    except :
        return None

空间中的空间是什么:这里和这是什么 return copy[:loc]

4

5 回答 5

2

我认为这些类型的转换的一个很好的过程是:

  • 弄清楚代码在做什么

  • 在 Python 中将其重构为 PHP 样式(这使您能够检查逻辑是否仍然有效,例如使用断言测试)。例如将列表推导转换为 for 循环

  • 转换为 PHP

例如,listspaces(string)返回 中空格的位置string,虽然使用列表推导是 Pythonic,但它不是很“PHP-onic”。

def listspaces2(string): #PHP-onic listspaces
    space_positions = []
    for i in range(len(string))]:
        if string[i] == ' ':
            space_positions.append(i)
    return space_positions

第二个例子trimcopy相当棘手(因为尝试,除了可能故意捕获一些预期的 - 对作者(!) - 异常 - 两个可能的string没有 alen并且spaces包含的​​值长于len(copy)),但很难说它是在 Python 中重构和测试的好主意。

您可以在 PHP 中进行数组切片,例如copy[:loc]使用array_slice($copy, 0, $loc);.

注意:通常在 Python 中,我们会明确说明我们要防御的异常(与Pokemon 异常处理相反)。

于 2012-09-26T11:35:40.107 回答
1

为什么不直接测试这些功能,看看它们在做什么?

listspaces(string)返回一个数组,其中包含字符串中所有空格的位置:

$ ipython
IPython 0.10.2 -- An enhanced Interactive Python.

In [1]: def listspaces(string):
   ...:     return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]
   ...:

In [2]: listspaces('Hallo du schöne neue Welt!')
Out[2]: [5, 8, 16, 21]

i -1是从零开始计数时空格的位置)

我对 Python 了解不多,也无法粘贴第二个函数,因为有很多“IndentationError”。

我认为这trimcopy()将返回一个字符串(来自 input copy),其中数组中给定的最后一个空格位置后面的所有内容spaces(显然是 from 的返回值listspaces())都会被修剪,除非输入不超过length. 换句话说:输入在小于 的最高空间位置被截断length

如上例所示,该部分' Welt!'将被切断:

s = 'Hallo du schöne neue Welt!'
trimcopy( s, listspaces( s ) )
/* should return: 'Hallo du schöne neue' */
于 2012-09-26T11:10:01.023 回答
1

你可能注意到第一个函数也可以写成

def listspaces(str):
    return [i for i, c in enumerate(str) if c==' ']

该版本具有以下对 PHP 的直接转换:

function listspaces($str) {
    $spaces = array();

    foreach (str_split($str) as $i => $chr)
        if ($chr == ' ') $spaces[] = $i;

    return $spaces;
}

至于其他功能,这似乎以几乎相同的习语做同样的事情:

function trimcopy($copy, $spaces, $length=350) {
    if (strlen($copy) < $length) {
        return $copy;
    } else {
        foreach ($spaces as $space) {
            if ($space < $length) {
                $loc = $space;
            } else {
                return substr($copy, 0, $loc);
            }
        }
    }
}

正如其他人所指出的,这两个函数的意图可能可以通过使用更好地表达wordwrap

于 2012-09-26T13:53:53.120 回答
0

第一个函数返回给定字符串中所有空格的索引。

  • range(len(string)) 结果列表中的数字从 0 到输入字符串的长度
  • if string.startswith(' ', i-1)]为每个索引评估条件i,当字符串(这里不是关键字)在索引给定的位置以 ' ' 开头时返回 truei-1

结果就像feela发布的那样。

对于第二个函数,我不知道空格参数是什么。

希望这将帮助您创建一个 PHP 版本。

于 2012-09-26T11:14:05.143 回答
0

这相当于 Python 中的两个函数

list($short) = explode("\n",wordwrap($string,350));
于 2012-09-26T13:52:51.243 回答