python处理PHP数组文本文件实例

yipeiwu_com5年前Python基础

需求:

对一个配置文件进行处理,拿出可用的字符来拼接,下面是原始文本,我们要得到这样的结果,

复制代码 代码如下:

redis -h 127.0.0.1 -p 6379 | select 2
redis -h 127.0.0.1 -p 6379 | select 16
redis -h 127.0.0.1 -p 6379 | select 8

原始文本:

复制代码 代码如下:

    'redis_list' => array(
        'normal' => array(
            'host' => '10.4.3.125',
            'port' => 6405,
            'db' => 6
        ), 
    'redis_list' => array(
        'normal' => array(
            'host' => '127.0.0.1',
            'port' => 6379,
            'db' => 2
        ), 
    'redis_list' => array(
        'normal' => array(
            'host' => '127.0.0.1',
            'port' => 6379,
            'db' => 16
        ), 
    'redis_list' => array(
        'normal' => array(
            'host' => '127.0.0.1',
            'port' => 6379,
            'db' => 8
        ),

上python:

复制代码 代码如下:

#!/usr/bin/env python
#coding=utf-8
import os

file=open("redis_list.txt", "r")
file_content=file.read()
php_array=file_content.replace("'normal' => array(","")
pstr = php_array.replace(" ","").replace("\r","").replace("\n", "").replace("\t", "").replace("(", "").replace("'", "").replace("),", "")
#print pstr
pstr_list = pstr.split("redis_list=>array")
#print type(pstr_list)

cf_param = []
for i in pstr_list:
 if i:
  ## 'host'=>'127.0.0.1','port'=>6411,'db'=>2
  i_list = i.split(",")
  if len(i_list)==3:
   op = {};
   for ii in i_list:
    ii_list = ii.split("=>")
    if len(ii_list) == 2:
     op[ii_list[0]] = ii_list[1]
   cf_param.append(op)

for i in cf_param:
    print "redis -h "+i["host"] + " -p "+i["port"] +"|select" +" "+i["db"]

相关文章

使用Python的判断语句模拟三目运算

下面说的和三目运算有点相似,但又不一样,实在不知道该如何拟定标题,先就是这个标题吧,大家都知道python中没有三目运算,但是and/or有点类似三目运算: and/or 单独使用表示逻...

浅谈Python数据类型之间的转换

Python数据类型之间的转换 函数 描述 int(x [,base])...

wxPython+Matplotlib绘制折线图表

wxPython+Matplotlib绘制折线图表

使用Matplotlib在wxPython的Panel上绘制曲线图,需要导入: import numpy from matplotlib.backends.backend_wxagg...

Python元组常见操作示例

本文实例讲述了Python元组常见操作。分享给大家供大家参考,具体如下: 不能修改的列表就叫做元组。 1 访问元素 元组是使用圆括号来标识的。 定义好元组后, 我们就可以使用索引来访问其...

Python正则表达式匹配HTML页面编码

html页面一般都会指定一个编码,如何获取到是处理html页面的第一步,因为错误的编码必然带来后面处理的问题。这里我用python的正则表达式写了个: import re a =...