社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将javascript函数转换为python

Maxime Morin-Gagnon • 6 年前 • 1795 次点击  

我是python的新手,我很难把这个javascript箭头函数翻译成python。当我找到'\x1d'时,我无法在JS中使用子字符串获取循环中接下来3个值的部分。有什么建议吗?

module.exports = edi => {
  let decompressedEdi = ''
  let lastCompressor = 0
  for (let i = 0; i <= edi.length; i++) {
    if (edi[i] === '\x1D') {
      let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
      let repeater = edi[i + 3]
      decompressedEdi +=
        edi.substring(lastCompressor, i) + repeater.repeat(decimal)
      lastCompressor = i + 4
    }
  }
  decompressedEdi += edi.substring(lastCompressor, edi.length)
  return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39353
文章 [ 2 ]  |  最新文章 6 年前
Thomas
Reply   •   1 楼
Thomas    6 年前
from re import sub

def decompress(edi):
    decompressed = ""
    last_compressor = 0

    for i, c in enumerate(edi):
        if c == "\x1D":
            repetitions = int(edi[i + 1: i + 3], 16)
            repeating_char = edi[i + 3]

            decompressed += edi[last_compressor:i] + repeating_char * repetitions
            last_compressor = i + 4

    decompressed += edi[last_compressor:-1]

    return sub("\r\n|\n|\r", decompressed)

我是怎么读代码的

可以忽略这一点,但这可能会有所帮助。

鉴于 edi 它有一个 len ,每个 电子数据交换 那是匹配的 \x1D ,获取的子字符串 EDI 来自 index + 1 index + 3 作为十六进制整数设置为 decimal 。这个 repeater 索引+3 '的第个元素 电子数据交换 str 。它将重复中定义的十六进制次数。 十进制的 ,但仅在 电子数据交换 lastCompressor 到当前索引。在每次迭代中 \x1D 是匹配的, 末级压缩机 增加4。

LVB
Reply   •   2 楼
LVB    6 年前

在python中,字符串可以像数组一样切片:

for i, c in enumerate(edi):
  if c == '\x1D':
    decimal = int(edi[i+1:i+3], 16)

int函数具有以下签名:int(str,base)