python到php代码转换

2024-09-30 14:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须把两个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或空格位置数组吗?在

第二个功能是

^{pr2}$

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


Tags: 函数inforstringlenreturnifdef
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!'将被切断:

^{pr2}$

我认为这类转换的一个好方法是:

  • 找出代码的作用

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

  • 转换为PHP

例如,listspaces(string)返回string中空格的位置,尽管使用列表理解是python的,但它不是很“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没有lenspaces包含的值长于len(copy)),但很难说,所以在Python中重构和测试是个好主意。在

您可以使用^{}在PHP中像copy[:loc]那样执行数组切片。在

注意:通常在Python中,我们会显式地声明我们要防御的异常(与Pokemon exception handling相反)。

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

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

该版本可以直接转换为PHP:

^{pr2}$

至于另一个函数,这似乎在几乎相同的习语中起着相同的作用:

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

相关问题 更多 >

    热门问题