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

yipeiwu_com6年前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 time模块

本文针对Python time模块进行分类学习,希望对大家的学习有所帮助。 一.壁挂钟时间 1.time() time模块的核心函数time(),它返回纪元开始的秒数,返回值为浮点数,具...

Python替换月份为英文缩写的实现方法

Python替换月份为英文缩写的实现方法

示例数据: zs,3 li,5 ww,10 cc,4 xm,2 xh,1 pp,6 qq,7 ff,11 dd,8 kk,12 mm,9 处理后效果: 脚本代码如下: 创建 文件名....

AI人工智能 Python实现人机对话

AI人工智能 Python实现人机对话

在人工智能进展的如火如荼的今天,我们如果不尝试去接触新鲜事物,马上就要被世界淘汰啦~ 本文拟使用Python开发语言实现类似于WIndows平台的“小娜”,或者是IOS下的“Siri”。...

pytorch 利用lstm做mnist手写数字识别分类的实例

代码如下,U我认为对于新手来说最重要的是学会rnn读取数据的格式。 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25...

Python3.6.2调用ffmpeg的方法

本文是为了学习python调用C语言的库写的例子。 去ffmpeg官网下载编译好的avcodec-57.dll、avutil-55.dll、swresample-2.dll,准备好了C语...