将php数组转换为python字典

2024-06-16 10:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我下载了一个看起来像PHP数组文件的文件,想知道是否有python模块或其他将数组转换/导入python字典的方法。 下面是PHP数组文件开头的示例。在

<?php

$legendre_roots = array();

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

理想情况下,我想要一本字典,例如:

^{pr2}$

感谢任何帮助。在


Tags: 模块文件方法示例字典情况数组array
3条回答

在我决定没有时间去处理JSON和PHP的复杂性之后,我决定编写一个python脚本来完成这项工作。它是基于纯文本处理的,如果需要的话可以被其他人修改。原文如此:

#!/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()

是的,它对我的情况非常特殊,但是如果有时间修改代码,并且在PHP-JSON方面得不到太多帮助,可能会对他们有所帮助。在

在PHP代码中添加一个小snipet,JSON对数组进行编码,并将其显示/存储在磁盘上。在

echo json_encode($legendre_roots)

您可能可以直接使用该JSON代码。如果不是,用python解码并pprint它。在

一个例子

<?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}}')

相关问题 更多 >