day27 模块:正则re, configparser, subprocess

Python之路,Day15 = Python基础15

re 模块补充

 1 ret = re.findall("c.d", "abc\nd", re.S)
 2     # 后面参数用来修改模式,这个模式下 . 可以匹配所有的字符,包括换行符
 3
 4
 5
 6 re.split()
 7     re.split("\d+", "hello23world12dfae3dge")
 8     >>>["hello", "world", "dfae", "dge"]
 9     可以第三个参数,最大分割次数。
10
11     re.split("(\d+)", "hello23world12dfae3dge")
12     >>>["hello", "23", "world", "12", "dfae", "3", "dge"]
13     分隔符用括号括起来,可以保留分隔符
14
15
16 re.sub()
17     re.sub(old, new, str, count)
18     re.sub(规则, 新的内容, 处理的字符串)
19     有返回值?
20
21 re.subn()
22     类似于 sub, 返回结果为一个元祖,第一个为返回的结果,第二个元素为替换的个数
23
24
25 re.compile()      # 编译
26
27 re.finditer()
28     结果为可迭代对象
29     res = re.finditer("","")
30     next(res).group()
31     # 封装到迭代器里面的是一个个对象

configparser 模块

  # 模块:用于文件处理
  # 可处理的文件类似于配置文件,文件的内容类似于嵌套的字典,文件格式:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
注:[DEFAULT] 为默认,里面存放的内容为下面都有的内容

用python生成这种文件

 1 import configparser
 2
 3 config = configparser.ConfigParser()
 4
 5 config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,
 6                       ‘Compression‘: ‘yes‘,
 7                      ‘CompressionLevel‘: ‘9‘,
 8                      ‘ForwardX11‘:‘yes‘
 9                      }
10
11 config[‘bitbucket.org‘] = {‘User‘:‘hg‘}
12
13 config[‘topsecret.server.com‘] = {‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘}
14
15 with open(‘example.ini‘, ‘w‘) as configfile:
16
17    config.write(configfile)

查找文件

 1 import configparser
 2
 3 config = configparser.ConfigParser()
 4
 5 #---------------------------查找文件内容,基于字典的形式
 6
 7 print(config.sections())        #  []
 8
 9 config.read(‘example.ini‘)
10
11 print(config.sections())        #   [‘bitbucket.org‘, ‘topsecret.server.com‘]
12
13 print(‘bytebong.com‘ in config) # False
14 print(‘bitbucket.org‘ in config) # True
15
16
17 print(config[‘bitbucket.org‘]["user"])  # hg
18
19 print(config[‘DEFAULT‘][‘Compression‘]) #yes
20
21 print(config[‘topsecret.server.com‘][‘ForwardX11‘])  #no
22
23
24 print(config[‘bitbucket.org‘])          #<Section: bitbucket.org>
25
26 for key in config[‘bitbucket.org‘]:     # 注意,有default会默认default的键
27     print(key)
28
29 print(config.options(‘bitbucket.org‘))  # 同for循环,找到‘bitbucket.org‘下所有键
30
31 print(config.items(‘bitbucket.org‘))    #找到‘bitbucket.org‘下所有键值对
32
33 print(config.get(‘bitbucket.org‘,‘compression‘)) # yes       get方法取深层嵌套的值

增删改操作

import configparser

config = configparser.ConfigParser()

config.read(‘example.ini‘)

config.add_section(‘yuan‘)

config.remove_section(‘bitbucket.org‘)
config.remove_option(‘topsecret.server.com‘,"forwardx11")

config.set(‘topsecret.server.com‘,‘k1‘,‘11111‘)
config.set(‘yuan‘,‘k2‘,‘22222‘)

config.write(open(‘new2.ini‘, "w")) 
时间: 2024-08-27 16:54:32

day27 模块:正则re, configparser, subprocess的相关文章

Python全栈 正则表达式(re模块正则接口全方位详解)

re模块是Python的标准库模块 模块正则接口的整体模式 re.compile 返回regetx对象 finditer fullmatch match search 返回 match对象 match.属性|方法 re模块的使用: regex = re.compile(pattern,flags = 0) 功能 : 生成正则表达式对象 参数 : pattern     正则表达式 flags  功能标志位,丰富正则表达式的匹配 返回值: 返回一个正则表达式对象 re.findall(patter

常用模块-----configparser &amp; subprocess

configparser 模块 功能:操作模块类的文件,configparser类型文件的操作类似于字典,大多数用法和字典相同. 新建文件: import configparser cfg=configparser.ConfigParser() cfg['DEFAULT']={'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } cfg['bitbucket

json&amp;pickle模块、configparse/hashlib/subprocess 模块

一.json 与pickle模块 序列化: 1.什么是序列化&反序列化 内存中的数据类型---->序列化---->特定的格式(json格式或者pickle格式) 内存中的数据类型<----反序列化<----特定的格式(json格式或者pickle格式) 2.为何要序列化 序列化得到结果=>特定的格式的内容有两种用途 1.可用于存储=>用于存档 2.传输给其他平台使用=>跨平台数据交互 ? 强调: 针对用途1的特定一格式:可是一种专用的格式=>pick

day6 反射,hashlib模块,正则匹配,冒泡,选择,插入排序

一.反射(自省) 首先通过一个例子来看一下本文中可能用到的对象和相关概念. import sys # 模块,sys指向这个模块对象import inspectdef foo(): pass # 函数,foo指向这个函数对象 class Cat(object): # 类,Cat指向这个类对象 def __init__(self, name='kitty'): self.name = name def sayHi(self): # 实例方法,sayHi指向这个方法对象,使用类或实例.sayHi访问

python 常用的模块 optparse与ConfigParser

一.optparse 模块 功能:optparse模块用于处理命令行参数 使用流程: 1.首先,必须 import OptionParser 类,创建一个 OptionParser 对象: from optparse import OptionParser def Opt ():    parser=OptionParser("Usage: %prog -o option -d domain -s subject") 2.使用 add_option 来定义命令行参数:    parse

Python使用re模块正则式的预编译及pickle方案

项目上线要求当中有言论和昵称的过滤需求, 客户端使用的是python脚本, python脚本中直接利用re模块来进行正则匹配, 一开始的做法是开启游戏后, 每帧编译2条正则式, 无奈运营需求里面100+条略为复杂的正则式, 一条编译起来在pc上都需要80ms, 造成客户端开启时候的卡顿. 解决方案当然是保存re模块编译的正则式结果, 之后开机直接加载就行, 然而需要注意的是re.compile()返回的_sre.SRE_Pattern对象虽然可以使用pickle保存下来, 但是这只是个假象, 实

python模块(shelve,xml,configparser,hashlib,logging)

1.1shelve模块 shelve 模块比pickle模块简单,只有一个open函数,返回类似字典对象,可读可写:key必须为字符串, 而值可以是python所支持的数据类型. shelve模块主要用来存储一个简单的数据, shelve最重要的函数是open,在调用它的时候,使用文件名作为参数,它会返回一个架子(shelf)对象,可以用它来存储类容. 1 f = shelve.open(r"shelve_test.txt") 2 # aa = {"stu1":{&

常用模块二(configparser

阅读目录 常用模块二 hashlib模块 configparse模块 logging模块 常用模块二 返回顶部 hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示). 摘要算法就是通过摘要函数f()对任意长度的数据data计算出固定长度的摘要digest,目的是为了发现原始数据是否被人篡改过. 摘要算法之所以能指出数

re模块 正则匹配

import re re.M 多行模式 位或的意思 parrterm就是正则表达式的字符串,flags是选项,表达式需要被编译,通过语法.策划.分析后卫其编译为一种格式,与字符串之间进行转换 re模块 主要为了提速,re的其他方法为了提高效率都调用了编译方法,就是为了提速 re的方法 单次匹配 re.compile 和 re.match def compile(pattern, flags=0): return _compile(pattern, flags) 可看到,re最后返回的是_comp