python - 将 pascal 转换为 python

标签 python

我有以下 Pascal 例程:

function TForm1.ldExtractFromLine (ldline: String; Post: Integer): String;
var
  s: String;
  t: array[1..15] of String;
  i, iT: Integer;
begin
  s := Trim(ldline);
  iT := 1;
  while s <> '' do
  begin
    s := Trim(s) + ' ';
    i := 1;
    while s[i] <> ' ' do Inc(i);
    t[iT] := Copy(s, 1, i-1);
    Inc(iT);
    s := Copy(s, i, Length(s));
  end;
  ldExtractFromLine := '';
  if Post < iT then ldExtractFromLine := t[Post];
end;

我正在尝试转换为Python。这是我到目前为止所拥有的:

def ldExtractFromLine (ldline, post):
    post -= 1    # mjh
    t = []

    s = ldline.strip()
    iT = 0;    # mjh
    while s <> '':
        s = s.strip() + ' '
        i = 0    # mjh
        while s[i] <> ' ': i += 1
#         t[iT] = Copy(s, 1, i-1)
#         function Copy(const S: string; From: integer = 1; Count: integer = MaxInt): string;
        t.insert(iT, s[0:i-1+1])    # mjh
        iT += 1
        s = s[i:(i+len(s)+1)]
        print "lala"

    result = ''
    if post < iT: result = t[post]    # mjh
    return result

但是,执行例程会导致无休止的“lala”打印到标准输出。问题是 Pascal 列表从索引 1 开始,而 Python 列表从索引 0 开始。这真的让我很困惑。谁能找到我的错误吗?变量 post 是一个通常小于 20 的整数。变量 ldline 是一个字符串,看起来有点像“1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat”。

[编辑]

可以在此处查看整个脚本:

https://github.com/Jeremy1980/LDBoxer

以下是一些输入数据示例:

0 Safe House
0 Name: building_013_safehouse.ldr
0 Author: Kevin Loch
0 ROTATION CENTER 0 0 0 1 "Custom"
0 ROTATION CONFIG 0 0
1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -20 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -20 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -100 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -100 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -180 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat
1 0 -180 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat

可以在此处找到输入数据的更多示例:

https://github.com/Jeremy1980/LDBoxer/issues/4

最佳答案

您的代码中的错误位于以下行:

s = s[i:(i+len(s)+1)]

您在字符串 s 中留下了一个前导空格,这会导致无限循环,并且 (i+len(s)+1) 部分是错误的。它可以替换为:

s = s[i+1:]

一般来说,这个 pascal 函数只是分割字符串并获取第 Post 个元素(从 1 开始)。等价的是这样的:

def ldExtractFromLine (ldline, post):
    a = ldline.split()
    if post <= len(a):
        return a[post-1]
    return ''   

关于python - 将 pascal 转换为 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182268/

相关文章:

python - 在类中定义函数时如何获取参数?

python - 使用 Numba 提取 numpy 数组中的特定行

python - 避免不必要地使用 lambda 调用对象方法

python - 为什么我的 python 3 实现比我用 C++ 编写的快得多?

python - django_language cookie 安全失败

python - 为什么这不返回给定数字的旋转?

python - 在 Windows 机器上运行 python 与 Linux

python - spark 可以将数据框拆分为 topandas 的部分

python - 附加到 python 字典

python - Pycurl PUT 请求到 JIRA REST API 等待 100 继续