Converting Python Code to PHP [closed]
Asked Answered
T

6

17

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')
Tumefaction answered 7/11, 2010 at 5:18 Comment(3)
Turns out the "software converter" was the user stillstanding.Tumefaction
Ha. Stack Overflow needs an API method where you can submit PHP code and get Python back!Gravesend
@Gravesend Universal-transpiler can convert a small subset of the PHP programming language into Python. It's still a work-in-progress, though.Parishioner
M
14

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));
Melbourne answered 7/11, 2010 at 5:29 Comment(9)
This is good, but you can't iterate over a string with foreach in PHP. You have to use for with numeric keys. As it is, this code gives an "Invalid argument supplied for foreach()" error.Gravesend
@stillstanding Well yes, of course you can if you convert it into an array first. Not a raw string though, as I noted.Gravesend
Also, this provides different results than the Python version - I wrote my own translation which was quite similar, and it was the same. Anyone know why? Python: "Bits of entropy in 'bubba dubba' is 22.44 " PHP: "Bits of entropy in 'bubba dubba' is 17.30"Gravesend
I'm thinking it's the log function? Python gives more digits of precision - math.log(2) is 0.69314718055994529, and PHP says log(2) is 0.69314718056. I'm surprised it adds up to such a difference.Gravesend
Given the fact that log(2) is the divisor and the digits precision are significant to some degree, the accumulated entropy can really be that much. php.net/manual/en/function.log.php has an example of a bclog() function for better precision.Melbourne
Python "float" maps onto C "double". Can PHP not do double precision math?Warlord
There are two stock PHP precision math libraries available: bcmath and GMP. PHP's default precision can be adjusted in php.ini up to a maximum of 16 digits (for most platforms).Melbourne
Great, assuming the OP needs it to return the same results as Python, the bclog suggested in the comments there should take care of it.Gravesend
I'm just going to say that all of you guys are awesome. I'm writing a research paper on password strength, and this has helped so much. Thanks!Tumefaction
R
11

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.

<?php
require_once('py2phplib.php');
require_once( 'math.php');
function calcNumEntropyBits($s) {
    if ((count($s) <= 0)) {
        return 0.0;
    }
    $symCount = array();
    foreach( $s as $c ) {
        if (!$symCount.__contains__($c)) {
            $symCount[$c] = 1;
        }
        else {
            $symCount[$c] += 1;
        }
    }
    $entropy = 0.0;
    foreach( $symCount->iteritems() as $temp_c ) {
        $prob = ($n / float(count($s)));
        $entropy += ($prob * (math::log($prob) / math::log(2)));
    }
    if (($entropy >= 0.0)) {
        return 0.0;
    }
    else {
        return -($entropy * count($s));
    }
}

function testEntropy($s) {
    pyjslib_printFunc(sprintf('Bits of entropy in \'%s\' is %.2f', new pyjslib_Tuple([$s, calcNumEntropyBits($s)])));
}

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

It would not run correctly due to the math import and __contains__, but those would be easy enough to fix by hand.

Ridden answered 28/11, 2015 at 21:49 Comment(0)
W
8

I am about 1/2 way done making a PHP interpreter in Python and I can tell you flat out that there are literally dozens of major edge cases that play out to thousands of possibilities that would make it almost impossible to port Python to PHP. Python has a much more robust grammar then PHP while further foward in the language, Python's stdlib is probably one of the most advanced in comparison to any other language in it's class.

My recommendation is to take your question one step further back, to why do you need a set of Python based logic in PHP. Alternatives to attempting to port/translate your code could include subprocessing from PHP to Python, using Gearman to have Python do work in the backend while PHP handles view logic, or a much more involved solution would be to implement a service bus or message queue between a PHP application and Python services.

PS. Apologies for any readability issues, finishing a 2 day sprint just now.

Withershins answered 7/11, 2010 at 5:48 Comment(0)
W
3

No such tool exists, you'll have to port the code yourself

Warlord answered 7/11, 2010 at 5:27 Comment(0)
D
2

I changed the library py2php from https://github.com/dan-da/py2php and forked it into a new repository at https://github.com/bunkahle/py2php You now can also use the python math library which is translated to PHP code. Still you have to do adaptations to your code in order to get it to work.

Diedra answered 10/2, 2019 at 13:2 Comment(0)
P
1

I wondered myself that same question, and I found this PyToPhp.py file in the GitHubGist site. It is simple, and seem an start point for the begining.

I'm going to take a look to it!!!

Phototopography answered 23/5, 2014 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.