用python合并两个PHP文件(PHP文件内容为array)

本文介绍了一种使用Python脚本合并两个PHP文件中数组的方法,确保了数组键的唯一性,并提供了完整的脚本示例及合并后的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

test文件内容:

<pre name="code" class="php"><?php 
return array(

    'a' => "AAAAAA",//sdfsfsdffd

    "b" => 'BBBBBB'

);
?>

 

test1文件内容:

<?php 
return array(

    'c' => "CCCCCC",//sdfsfsdffd

    "d" => 'DDDDDD',

);
?>

假设这两个文件的array的key一定不一样,需要将这两个文件合并起来。

python脚本如下:

#coding:utf-8
import os
import re
file1 = 'C:\\Users\\Administrator\\Desktop\\test.php'
file2 = 'C:\\Users\\Administrator\\Desktop\\test1.php'
def read_file(source_file):
    dic = dict()
    if os.path.exists(source_file):
        content = read_content(source_file)

        preg = re.compile('(array\(.*\))',re.DOTALL)
        rtn = preg.search(content)
        if len(rtn.groups()) > 0:
            rtn = rtn.groups()[0]
            rtn = rtn.replace("array(","").replace(")","")
            rtns = rtn.split("\n")
            for line in rtns:
                if len(line.strip()) == 0:
                    continue
                lines = line.split("=>")
                lines[0] = lines[0].strip()
                lines[1] = lines[1].strip()
                if lines[0].find("\"") == 0:
                    lines[0] = lines[0][lines[0].find("\"")+1:lines[0].rfind("\"")]
                elif lines[0].find("'") == 0:
                    lines[0] = lines[0][lines[0].find("'")+1:lines[0].rfind("'")]
                if lines[1].find("\"") == 0:
                    lines[1] = lines[1][lines[1].find("\"")+1:lines[1].rfind("\"")]
                elif lines[1].find("'") == 0:
                    lines[1] = lines[1][lines[1].find("'")+1:lines[1].rfind("'")]
                dic[lines[0]] = lines[1]

    return dic

def read_content(source_file):
    handle = open(source_file,'r')
    content = handle.read()
    handle.close() 
    return content

def write_file(dst_file,content,dic):
    handle = open(dst_file,'w')
    handle.write(content)
    for key in dic.keys():
        line = "\n    \"%s\"=>\"%s\","%(key,dic[key])
        handle.write(line)
    handle.write("\n);\n?>")
    handle.close()

def merge():
    dic = read_file(file2)
    content = read_content(file1)

    content = content.replace("?>","").replace(");","").strip()
    if content[-1] != ',':
        content += ','
    write_file(file1,content,dic)

if __name__ == '__main__':
    merge()
    print 'done!'

合并后的文件内容为:

<?php 
return array(

    'a' => "AAAAAA",//sdfsfsdffd

    "b" => 'BBBBBB',
    "c"=>"CCCCCC",
    "d"=>"DDDDDD",
);
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值