Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Python Code to PHP [closed]

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')
like image 232
Kirk Ouimet Avatar asked Nov 07 '10 05:11

Kirk Ouimet


People also ask

Can I convert Python code to PHP?

I created a python-to-php converter called py2php. It can auto-translate the basic logic and then you will need to tweak library calls, etc. Still experimental. Here is auto-generated PHP from the python provided by the OP.

Can you mix Python and PHP?

Yes it is possible.

How do I connect Python to PHP?

php $command_exec = escapeshellcmd('path-to-. py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user.


1 Answers

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');

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));
like image 60
bcosca Avatar answered Sep 20 '22 20:09

bcosca