我已经下载了类似于PHP数组文件的内容,并想知道是否有python模块或其他方式将数组转换/导入python字典。 以下是PHP数组文件开头的示例。
<?php
$legendre_roots = array();
$legendre_roots[2] = array(
-0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168,
0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168);
我理想情况下会喜欢一本字典,例如:
legendre_roots = { 2: [-0.57735,0.57735], 3: [.......]......}
任何帮助表示感谢。
答案 0 :(得分:2)
示例
<?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}}')
答案 1 :(得分:1)
在PHP代码中添加一个小型snipet,JSON对该数组进行编码,并将其显示/存储在磁盘上。
echo json_encode($legendre_roots)
您可以直接使用该JSON代码。如果没有,请在python和pprint
中对其进行解码。
答案 2 :(得分:0)
在决定我没有时间搞乱JSON和PHP错综复杂之后,我决定编写一个python脚本来完成这项工作。它基于纯文本处理,如果需要可以由其他人进行调整。 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()
是的,这是非常具体的我的情况,但如果他们有时间调整代码并且没有得到PHP JSON的帮助,可能会帮助那些人。