【问题标题】:python to php code conversionpython到php代码转换
【发布时间】:2012-09-26 21:53:53
【问题描述】:

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

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

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

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

在 PHP 中,我们使用 [] 表示数组。这里我们是[],有返回,这个函数会返回真假还是空格位置数组?

第二个功能是

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]

【问题讨论】:

  • 检查python列表理解,for循环和python切片......
  • 这些都是很奇怪的函数(尤其是trimcopy)!
  • 我想出这个作为两个函数的 php 替代 list($short) = explode("\n",wordwrap($string,100));这是正确的吗?
  • 这不太行,在 trimcopy 的 else 块中试试这个位: list($newtext) = explode(" ",wordwrap($string,350," "));,但是很难说出函数的意图(因为它肯定有问题)!

标签: php python converter


【解决方案1】:

我认为此类转换的一个好的过程是:

  • 弄清楚代码在做什么

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

  • 转换为 PHP

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

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 相当棘手(因为尝试,except 可能故意捕捉一些预期 - 对作者来说(!) - 异常 - 两种可能是 string 没有 len 和 @987654329 @ 包含比 len(copy) 更长的值),但很难说,所以在 Python 中重构和测试是个好主意。

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

注意:通常在 Python 中,我们会明确说明我们要防御的异常(而不是 Pokemon exception handling)。

【讨论】:

  • try … except:我猜这是因为如果copy 确实至少包含loc 字符在copy[:loc].+ 中,则不会在任何地方检查它。
  • @feeela 我也猜到了……但它可能在其余代码中隐藏了一些险恶的错误!
  • 我想出这个作为两个函数的 php 替代 list($short) = explode("\n",wordwrap($string,100));这是正确的吗?
  • 几乎,这在 trimcopy 中的 else 块内的位:list($newtext) = explode(" ",wordwrap($string,350," ",true));,虽然很难说出函数的意图(因为它肯定是错误的)!
  • @hayden,谢谢 我会添加这一行 if (strlen($string) > 350) { list($newtext) = explode(" ",wordwrap($string,350," ",true )); }
【解决方案2】:

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

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 可能更好地表达这两个函数的意图。

【讨论】:

  • 谢谢,你同意这一行作为这两个函数的替代吗 list($short) = explode("\n",wordwrap($string,350));
  • 如果它们只是组合使用,它们似乎就是为了做到这一点而设计的。就此而言,您可以在 python 的标准库中使用 textwrap.wrap。
【解决方案3】:

您为什么不直接测试这些函数,看看它们在做什么?

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() 将返回一个字符串(来自输入copy),其中数组spaces 中给出的最后一个空格位置后面的所有内容(显然是来自listspaces() 的返回值)都被修剪,除非输入不超过length。 换句话说:输入在小于length的最高空间位置被截断。

如上例,' Welt!' 部分将被截断:

s = 'Hallo du schöne neue Welt!'
trimcopy( s, listspaces( s ) )
/* should return: 'Hallo du schöne neue' */

【讨论】:

  • 我试过了,第一个是返回位置数组,第二个没有做任何事情,它返回相同的文本但修剪版本
  • 如果副本长于长度,则返回第一个空格之前的副本块,这可能比长度长也可能不长,这种行为不好......
  • @hayden 好吧,这些函数不是我写的……
  • @feeela 我知道!但是比较'a '*100'a '*200'a'*400 的输出很有趣。 :)
  • 我想出这个作为两个函数的 php 替代 list($short) = explode("\n",wordwrap($string,100));这是正确的吗?
【解决方案4】:

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

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

结果如 feela 发布的那样。

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

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

【讨论】:

    【解决方案5】:

    这相当于Python中的两个函数

    list($short) = explode("\n",wordwrap($string,350));
    

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多