English 中文(简体)
Converting Python Code to PHP [closed]
原标题:

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 2 years ago.

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 )
最佳回答

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));
问题回答

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.

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.

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

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.

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!!!





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签