Jacques MALAPRADE
Jacques MALAPRADE

Reputation: 1013

Convert a php array to a python dictionary

I have downloaded what looks like a PHP array file, and wondering if there is a python module or another way of converting/importing the array to a python dictionary. Here is a sample of the start of the PHP array file.

<?php

$legendre_roots = array();

$legendre_roots[2] = array(
-0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168,
0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168);

I would ideally like a dictionary with for example:

legendre_roots = { 2: [-0.57735,0.57735], 3: [.......]......}

Any help appreciated.

Upvotes: 1

Views: 5108

Answers (3)

Jacques MALAPRADE
Jacques MALAPRADE

Reputation: 1013

After deciding I don't have the time to mess with JSON and PHP intricacies I decided to write a python script to do the job. It is based on pure textual processing and can be adapted by other if needed. sic:

#!/usr/bin/python

''' A file that will read the text in the php file and add each array as 
a dictionary item to a dictionary and saves it as a dictionary.
'''
import pickle
import pdb

file_name = 'lgvalues-abscissa.php'
#file_name = 'lgvalues-weights.php'
text = 'legendre_roots['
#text = 'quadrature_weights['


def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False

mydict = dict()
lst = []
ft = open(file_name,'rt')
file_lines = ft.readlines()
for i, l in enumerate(file_lines):
  if l.find(text) != -1:
    key = l.split()[0]
    key = [key[l.find('[')+1:l.find(']')],]
    continue
  if is_number(l.strip()[:16]): 
    lst.append(float(l.strip()[:16]))
    if l.strip()[-2:] == ');':
      if int(key[0]) != len(lst):
        print 'key %s does not have the right amount of items.'\
            %(key[0])
      tempdict = {}
      tempdict = tempdict.fromkeys(key,lst)
      mydict.update(tempdict)

      lst = []

file_name = file_name[:-4]+'.dat'
fb = open(file_name,'wb')
pickle.dump(mydict,fb)
print 'Dictionary file saved to %s' % (file_name)
fb.close()

Yes it is very specific to my case but may help someone out there if they have the time to adapt the code and don't get much help with PHP JSON otherwise.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96266

Add to the PHP code a small snipet which JSON encodes the array, and displays / stores it on the disk.

echo json_encode($legendre_roots)

You can probably use that JSON code directly. if not, decode it in python and pprint it.

Upvotes: 1

Shinto Joseph
Shinto Joseph

Reputation: 1171

AN EXAMPLE

<?php
$arr = array('test' => 1, 'ing' => 2, 'curveball' => array(1, 2, 3=>4) );
echo json_encode($arr);
?>

# elsewhere, in Python...
import simplejson
print simplejson.loads('{"test":1,"ing":2,"curveball":{"0":1,"1":2,"3":4}}')

Upvotes: 4

Related Questions