将Python代码转换为PHP [英] Converting Python Code to PHP

查看:699
本文介绍了将Python代码转换为PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那里有一个可以自动将此python代码转换为PHP的软件转换器吗?

Is there a software converter out there that can automatically convert this python code to PHP?

#!/usr/bin/python
import math

def calcNumEntropyBits(s):
        if len(s) <= 0: return 0.0
        symCount = {}
        for c in s:
                if c not in symCount: symCount[c] = 1
                else: symCount[c] += 1
        entropy = 0.0
        for c,n in symCount.iteritems():
                prob = n / float(len(s))
                entropy += prob * (math.log(prob)/math.log(2))
        if entropy >= 0.0: return 0.0
        else: return -(entropy*len(s))

def testEntropy(s):
        print "Bits of entropy in '%s' is %.2f" % (s, calcNumEntropyBits(s))

testEntropy('hello world')
testEntropy('bubba dubba')
testEntropy('aaaaaaaaaaa')
testEntropy('aaaaabaaaaa')
testEntropy('abcdefghijk')

推荐答案

我不知道在野外有任何Python到PHP的转换器,但是移植它应该是一件微不足道的任务,相似之处很容易实现点:

I'm not aware of any Python-to-PHP converter in the wild, but it should be a trivial task to port and the similarities are quite easy to spot:

function calcNumEntropyBits($s) {
        if (strlen($s) <= 0) return 0.0;
        $symCount = array();
        foreach (str_split($s) as $c) {
                if (!in_array($c,$symCount)) $symCount[$c] = 1;
                else $symCount[$c] ++;
        }
        $entropy = 0.0;
        foreach ($symCount as $c=>$n) {
                $prob = $n / (float)strlen($s);
                $entropy += $prob * log($prob)/log(2);
        }
        if ($entropy >= 0.0) return 0.0;
        else return -($entropy*strlen($s));
}

function testEntropy($s):
        printf("Bits of entropy in '%s' is %.2f",$s,calcNumEntropyBits($s));

testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');

第一个函数的最后几行也可能被编写为标准的PHP三元表达式:

The last few lines in the first function could have also been written as a standard PHP ternary expression:

return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));

这篇关于将Python代码转换为PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆