re模块

一:什么是正则?

 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

生活中处处都是正则:

    比如我们描述:4条腿

      你可能会想到的是四条腿的动物或者桌子,椅子等

    继续描述:4条腿,活的

          就只剩下四条腿的动物这一类了

二:常用匹配模式(元字符)

  1. # =================================匹配模式=================================
  2. #一对一的匹配
  3. # 'hello'.replace(old,new)
  4. # 'hello'.find('pattern')
  5.  
  6. #正则匹配
  7. import re
  8. #\w与\W
  9. print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
  10. print(re.findall('\W','hello egon 123')) #[' ', ' ']
  11.  
  12. #\s与\S
  13. print(re.findall('\s','hello egon 123')) #[' ', ' ', ' ', ' ']
  14. print(re.findall('\S','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
  15.  
  16. #\n \t都是空,都可以被\s匹配
  17. print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']
  18.  
  19. #\n与\t
  20. print(re.findall(r'\n','hello egon \n123')) #['\n']
  21. print(re.findall(r'\t','hello egon\t123')) #['\n']
  22.  
  23. #\d与\D
  24. print(re.findall('\d','hello egon 123')) #['1', '2', '3']
  25. print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
  26.  
  27. #\A与\Z
  28. print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
  29. print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$
  30.  
  31. #^与$
  32. print(re.findall('^h','hello egon 123')) #['h']
  33. print(re.findall('3$','hello egon 123')) #['3']
  34.  
  35. # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
  36. #.
  37. print(re.findall('a.b','a1b')) #['a1b']
  38. print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
  39. print(re.findall('a.b','a\nb')) #[]
  40. print(re.findall('a.b','a\nb',re.S)) #['a\nb']
  41. print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样
  42.  
  43. #*
  44. print(re.findall('ab*','bbbbbbb')) #[]
  45. print(re.findall('ab*','a')) #['a']
  46. print(re.findall('ab*','abbbb')) #['abbbb']
  47.  
  48. #?
  49. print(re.findall('ab?','a')) #['a']
  50. print(re.findall('ab?','abbb')) #['ab']
  51. #匹配所有包含小数在内的数字
  52. print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
  53.  
  54. #.*默认为贪婪匹配
  55. print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
  56.  
  57. #.*?为非贪婪匹配:推荐使用
  58. print(re.findall('a.*?b','a1b22222222b')) #['a1b']
  59.  
  60. #+
  61. print(re.findall('ab+','a')) #[]
  62. print(re.findall('ab+','abbb')) #['abbb']
  63.  
  64. #{n,m}
  65. print(re.findall('ab{2}','abbb')) #['abb']
  66. print(re.findall('ab{2,4}','abbb')) #['abb']
  67. print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
  68. print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'
  69.  
  70. #[]
  71. print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
  72. print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
  73. print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
  74. print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
  75. print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']
  76.  
  77. #\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
  78. print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
  79. print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']
  80.  
  81. #():分组
  82. print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
  83. print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
  84. print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
  85. print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
  86. print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']
  87.  
  88. #|
  89. print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))

  

  1. mport re
  2. # print(re.findall('\w','ab 12\+- *&_'))
  3. # \w
  4. # print(re.findall('\W','ab 12\+- *&_'))
  5. # print(re.findall('\s','ab \r1\n2\t\+- *&_'))
  6. # print(re.findall('\S','ab \r1\n2\t\+- *&_'))
  7. # print(re.findall('\d','ab \r1\n2\t\+- *&_'))
  8. # \d
  9. # print(re.findall('\D','ab \r1\n2\t\+- *&_'))
  10.  
  11. # print(re.findall('\w_sb','egon alex_sb123123wxx_sb,lxx_sb'))
  12. # \w_sb
  13.  
  14. # print(re.findall('\Aalex','abcalex is salexb'))
  15. # print(re.findall('\Aalex','alex is salexb'))
  16. # print(re.findall('^alex','alex is salexb'))
  17. # print(re.findall('sb\Z','alexsb is sbalexbsb'))
  18. # print(re.findall('sb$','alexsb is sbalexbsb'))
  19. # sb
  20.  
  21. # print(re.findall('^ebn$','ebn1'))
  22. # ebn
  23.  
  24. # print(re.findall('a\nc','a\nc a\tc a1c'))
  25.  
  26. # 重复匹配:
  27. #. ? * + {m,n} .* .*?
  28. #1、.:代表除了换行符外的任意一个字符
  29. # print(re.findall('a.c','abc a1c aAc aaaaaca\nc'))
  30. # a.c
  31. # print(re.findall('a.c','abc a1c aAc aaaaaca\nc',re.DOTALL))
  32.  
  33. #2、?:代表左边那一个字符重复0次或1次
  34. # print(re.findall('ab?','a ab abb abbb abbbb abbbb'))
  35. # ab?
  36.  
  37. #3、*:代表左边那一个字符出现0次或无穷次
  38. # print(re.findall('ab*','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  39. # ab*
  40.  
  41. #4、+ :代表左边那一个字符出现1次或无穷次
  42. # print(re.findall('ab+','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  43. # ab+
  44.  
  45. #5、{m,n}:代表左边那一个字符出现m次到n次
  46. # print(re.findall('ab?','a ab abb abbb abbbb abbbb'))
  47. # print(re.findall('ab{0,1}','a ab abb abbb abbbb abbbb'))
  48.  
  49. # print(re.findall('ab*','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  50. # print(re.findall('ab{0,}','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  51.  
  52. # print(re.findall('ab+','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  53. # print(re.findall('ab{1,}','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  54.  
  55. # print(re.findall('ab{1,3}','a ab abb abbb abbbb abbbb a1bbbbbbb'))
  56.  
  57. #6、.*:匹配任意长度,任意的字符=====》贪婪匹配
  58. # print(re.findall('a.*c','ac a123c aaaac a *123)()c asdfasfdsadf'))
  59. # a.*c
  60.  
  61. #7、.*?:非贪婪匹配
  62. # print(re.findall('a.*?c','a123c456c'))
  63.  
  64. # ():分组
  65. # print(re.findall('(alex)_sb','alex_sb asdfsafdafdaalex_sb'))
  66.  
  67. # (alex)_sb
  68.  
  69. # print(re.findall(
  70. # 'href="(.*?)"',
  71. # '<li><a id="blog_nav_sitehome" class="menu" href="http://www.cnblogs.com/">博客园</a></li>')
  72. # )
  73. # <li><a id="blog_nav_sitehome" class="menu" href="http://www.cnblogs.com/">博客园</a></li>
  74. # href=".*?"
  75.  
  76. # []:匹配一个指定范围内的字符(这一个字符来自于括号内定义的)
  77. # print(re.findall('a[0-9][0-9]c','a1c a+c a2c a9c a11c a-c acc aAc'))
  78.  
  79. #当-需要被当中普通符号匹配时,只能放到[]的最左边或最 右边
  80. # print(re.findall('a[-+*]c','a1c a+c a2c a9c a*c a11c a-c acc aAc'))
  81.  
  82. # print(re.findall('a[a-zA-Z]c','a1c a+c a2c a9c a*c a11c a-c acc aAc'))
  83.  
  84. # []内的^代表取反的意思
  85. # print(re.findall('a[^a-zA-Z]c','a c a1c a+c a2c a9c a*c a11c a-c acc aAc'))
  86. # print(re.findall('a[^0-9]c','a c a1c a+c a2c a9c a*c a11c a-c acc aAc'))
  87.  
  88. # print(re.findall('([a-z]+)_sb','egon alex_sb123123wxxxxxxxxxxxxx_sb,lxx_sb'))
  89. # [a-z]+_sb
  90.  
  91. # | :或者
  92. # print(re.findall('compan(ies|y)','Too many companies have gone bankrupt, and the next one is my company'))
  93.  
  94. # (?:):代表取匹配成功的所有内容,而不仅仅只是括号内的内容
  95. # print(re.findall('compan(?:ies|y)','Too many companies have gone bankrupt, and the next one is my company'))
  96.  
  97. # print(re.findall('alex|sb','alex sb sadfsadfasdfegon alex sb egon'))
  98.  
  99. # re模块的其他方法:
  100. # print(re.findall('alex|sb','123123 alex sb sadfsadfasdfegon alex sb egon'))
  101. # print(re.search('alex|sb','123213 alex sb sadfsadfasdfegon alex sb egon').group())
  102. # print(re.search('^alex','123213 alex sb sadfsadfasdfegon alex sb egon'))
  103.  
  104. # print(re.search('^alex','alex sb sadfsadfasdfegon alex sb egon').group())
  105. # print(re.match('alex','alex sb sadfsadfasdfegon alex sb egon').group())
  106. # print(re.match('alex','123213 alex sb sadfsadfasdfegon alex sb egon'))
  107.  
  108. # info='a:b:c:d'
  109. # print(info.split(':'))
  110. # print(re.split(':',info))
  111.  
  112. # info=r'get :a.txt\3333/rwx'
  113. # print(re.split('[ :\\\/]',info))
  114.  
  115. # print('egon is beutifull egon'.replace('egon','EGON',1))
  116.  
  117. # print(re.sub('(.*?)(egon)(.*?)(egon)(.*?)',r'\1\2\3EGON\5','123 egon is beutifull egon 123'))
  118.  
  119. # (123 )(egon)( is beutifull )(egon)( 123)
  120.  
  121. #\1\2\3EGON\5
  122.  
  123. # print(re.sub('(lqz)(.*?)(SB)',r'\3\2\1',r'lqz is SB'))
  124. # print(re.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)',r'\5\2\3\4\1',r'lqzzzz123+ is SB'))
  125.  
  126. #(lqzzzz)(123+ )(is)( )(SB)
  127.  
  128. pattern=re.compile('alex')
  129. print(pattern.findall('alex is alex alex'))
  130. print(pattern.findall('alexasdfsadfsadfasdfasdfasfd is alex alex'))
  1. #为何同样的表达式search与findall却有不同结果:
  2. print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)
  3. print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']
  4.  
  5. #看这个例子:(\d)+相当于(\d)(\d)(\d)(\d)...,是一系列分组
  6. print(re.search('(\d)+','').group()) #group的作用是将所有组拼接到一起显示出来

search与findall

  1. #_*_coding:utf-8_*_
  2. __author__ = 'Linhaifeng'
  3. #在线调试工具:tool.oschina.net/regex/#
  4. import re
  5.  
  6. s='''
  7. http://www.baidu.com
  8. egon@oldboyedu.com
  9. 你好
  10. 010-3141
  11. '''
  12.  
  13. #最常规匹配
  14. # content='Hello 123 456 World_This is a Regex Demo'
  15. # res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content)
  16. # print(res)
  17. # print(res.group())
  18. # print(res.span())
  19.  
  20. #泛匹配
  21. # content='Hello 123 456 World_This is a Regex Demo'
  22. # res=re.match('^Hello.*Demo',content)
  23. # print(res.group())
  24.  
  25. #匹配目标,获得指定数据
  26.  
  27. # content='Hello 123 456 World_This is a Regex Demo'
  28. # res=re.match('^Hello\s(\d+)\s(\d+)\s.*Demo',content)
  29. # print(res.group()) #取所有匹配的内容
  30. # print(res.group(1)) #取匹配的第一个括号内的内容
  31. # print(res.group(2)) #去陪陪的第二个括号内的内容
  32.  
  33. #贪婪匹配:.*代表匹配尽可能多的字符
  34. # import re
  35. # content='Hello 123 456 World_This is a Regex Demo'
  36. #
  37. # res=re.match('^He.*(\d+).*Demo$',content)
  38. # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
  39.  
  40. #非贪婪匹配:?匹配尽可能少的字符
  41. # import re
  42. # content='Hello 123 456 World_This is a Regex Demo'
  43. #
  44. # res=re.match('^He.*?(\d+).*Demo$',content)
  45. # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
  46.  
  47. #匹配模式:.不能匹配换行符
  48. content='''Hello 123456 World_This
  49. is a Regex Demo
  50. '''
  51. # res=re.match('He.*?(\d+).*?Demo$',content)
  52. # print(res) #输出None
  53.  
  54. # res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.可以匹配换行符
  55. # print(res)
  56. # print(res.group(1))
  57.  
  58. #转义:\
  59.  
  60. # content='price is $5.00'
  61. # res=re.match('price is $5.00',content)
  62. # print(res)
  63. #
  64. # res=re.match('price is \$5\.00',content)
  65. # print(res)
  66.  
  67. #总结:尽量精简,详细的如下
  68. # 尽量使用泛匹配模式.*
  69. # 尽量使用非贪婪模式:.*?
  70. # 使用括号得到匹配目标:用group(n)去取得结果
  71. # 有换行符就用re.S:修改模式
  72.  
  73. #re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回
  74.  
  75. # import re
  76. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  77. #
  78. # res=re.match('Hello.*?(\d+).*?Demo',content)
  79. # print(res) #输出结果为None
  80.  
  81. #
  82. # import re
  83. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  84. #
  85. # res=re.search('Hello.*?(\d+).*?Demo',content) #
  86. # print(res.group(1)) #输出结果为
  87.  
  88. #re.search:只要一个结果,匹配演练,
  89. import re
  90. content='''
  91. <tbody>
  92. <tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk "><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&amp;quality=100"></a><span data-res-id="476630320" "
  93. # res=re.search('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
  94. # print(res.group(1))
  95.  
  96. #re.findall:找到符合条件的所有结果
  97. # res=re.findall('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
  98. # for i in res:
  99. # print(i)
  100.  
  101. #re.sub:字符串替换
  102. import re
  103. content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  104.  
  105. # content=re.sub('\d+','',content)
  106. # print(content)
  107.  
  108. #用\1取得第一个括号的内容
  109. #用法:将123与456换位置
  110. # import re
  111. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  112. #
  113. # # content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content)
  114. # content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content)
  115. # print(content)
  116.  
  117. # import re
  118. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  119. #
  120. # res=re.search('Extra.*?(\d+).*strings',content)
  121. # print(res.group(1))
  122.  
  123. # import requests,re
  124. # respone=requests.get('https://book.douban.com/').text
  125.  
  126. # print(respone)
  127. # print('======'*1000)
  128. # print('======'*1000)
  129. # print('======'*1000)
  130. # print('======'*1000)
  131. # res=re.findall('<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>',respone,re.S)
  132. # # res=re.findall('<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>',respone,re.S)
  133. #
  134. #
  135. # for i in res:
  136. # print('%s %s %s %s' %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))

shelve模块

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

  1. import shelve
  2.  
  3. f=shelve.open(r'sheve.txt')
  4. # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
  5. # f['stu2_info']={'name':'gangdan','age':53}
  6. # f['school_info']={'website':'http://www.pypy.org','city':'beijing'}
  7.  
  8. print(f['stu1_info']['hobby'])
  9. f.close()

xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

  1. <?xml version="1.0"?>
  2. <data>
  3. <country name="Liechtenstein">
  4. <rank updated="yes">2</rank>
  5. <year>2008</year>
  6. <gdppc>141100</gdppc>
  7. <neighbor name="Austria" direction="E"/>
  8. <neighbor name="Switzerland" direction="W"/>
  9. </country>
  10. <country name="Singapore">
  11. <rank updated="yes">5</rank>
  12. <year>2011</year>
  13. <gdppc>59900</gdppc>
  14. <neighbor name="Malaysia" direction="N"/>
  15. </country>
  16. <country name="Panama">
  17. <rank updated="yes">69</rank>
  18. <year>2011</year>
  19. <gdppc>13600</gdppc>
  20. <neighbor name="Costa Rica" direction="W"/>
  21. <neighbor name="Colombia" direction="E"/>
  22. </country>
  23. </data>
  24.  
  25. xml数据

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:

  1. # print(root.iter('year')) #全文搜索
  2. # print(root.find('country')) #在root的子节点找,只找一个
  3. # print(root.findall('country')) #在root的子节点找,找所有

  

  1. import xml.etree.ElementTree as ET
  2.  
  3. tree = ET.parse("xmltest.xml")
  4. root = tree.getroot()
  5. print(root.tag)
  6.  
  7. #遍历xml文档
  8. for child in root:
  9. print('========>',child.tag,child.attrib,child.attrib['name'])
  10. for i in child:
  11. print(i.tag,i.attrib,i.text)
  12.  
  13. #只遍历year 节点
  14. for node in root.iter('year'):
  15. print(node.tag,node.text)
  16. #---------------------------------------
  17.  
  18. import xml.etree.ElementTree as ET
  19.  
  20. tree = ET.parse("xmltest.xml")
  21. root = tree.getroot()
  22.  
  23. #修改
  24. for node in root.iter('year'):
  25. new_year=int(node.text)+1
  26. node.text=str(new_year)
  27. node.set('updated','yes')
  28. node.set('version','1.0')
  29. tree.write('test.xml')
  30.  
  31. #删除node
  32. for country in root.findall('country'):
  33. rank = int(country.find('rank').text)
  34. if rank > 50:
  35. root.remove(country)
  36.  
  37. tree.write('output.xml')
  1. #在country内添加(append)节点year2
  2. import xml.etree.ElementTree as ET
  3. tree = ET.parse("a.xml")
  4. root=tree.getroot()
  5. for country in root.findall('country'):
  6. for year in country.findall('year'):
  7. if int(year.text) > 2000:
  8. year2=ET.Element('year2')
  9. year2.text='新年'
  10. year2.attrib={'update':'yes'}
  11. country.append(year2) #往country节点下添加子节点
  12.  
  13. tree.write('a.xml.swap')

configparser模块

  1. # 注释1
  2. ; 注释2
  3.  
  4. [section1]
  5. k1 = v1
  6. k2:v2
  7. user=egon
  8. age=18
  9. is_admin=true
  10. salary=31
  11.  
  12. [section2]
  13. k1 = v1
  1. import configparser
  2.  
  3. config=configparser.ConfigParser()
  4. config.read('a.cfg')
  5.  
  6. #查看所有的标题
  7. res=config.sections() #['section1', 'section2']
  8. print(res)
  9.  
  10. #查看标题section1下所有key=value的key
  11. options=config.options('section1')
  12. print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
  13.  
  14. #查看标题section1下所有key=value的(key,value)格式
  15. item_list=config.items('section1')
  16. print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
  17.  
  18. #查看标题section1下user的值=>字符串格式
  19. val=config.get('section1','user')
  20. print(val) #egon
  21.  
  22. #查看标题section1下age的值=>整数格式
  23. val1=config.getint('section1','age')
  24. print(val1) #18
  25.  
  26. #查看标题section1下is_admin的值=>布尔值格式
  27. val2=config.getboolean('section1','is_admin')
  28. print(val2) #True
  29.  
  30. #查看标题section1下salary的值=>浮点型格式
  31. val3=config.getfloat('section1','salary')
  32. print(val3) #31.0
  1. import configparser
  2.  
  3. config=configparser.ConfigParser()
  4. config.read('a.cfg',encoding='utf-8')
  5.  
  6. #删除整个标题section2
  7. config.remove_section('section2')
  8.  
  9. #删除标题section1下的某个k1和k2
  10. config.remove_option('section1','k1')
  11. config.remove_option('section1','k2')
  12.  
  13. #判断是否存在某个标题
  14. print(config.has_section('section1'))
  15.  
  16. #判断标题section1下是否有user
  17. print(config.has_option('section1',''))
  18.  
  19. #添加一个标题
  20. config.add_section('egon')
  21.  
  22. #在标题egon下添加name=egon,age=18的配置
  23. config.set('egon','name','egon')
  24. config.set('egon','age',18) #报错,必须是字符串
  25.  
  26. #最后将修改的内容写入文件,完成最终的修改
  27. config.write(open('a.cfg','w'))

  

常用模块re模块(正则表达式)的更多相关文章

  1. python-Day5-深入正则表达式--冒泡排序-时间复杂度 --常用模块学习:自定义模块--random模块:随机验证码--time & datetime模块

    正则表达式   语法:             mport re #导入模块名 p = re.compile("^[0-9]") #生成要匹配的正则对象 , ^代表从开头匹配,[0 ...

  2. 常用模块 re模块与正则表达式

    re模块 正则: 正则就是用一些具有特殊含义的符号组合到一起(称之为正则表达式)来描述字符或字符串的方法.或者说:正则就是用描述一类事物的规则.(在python中) 它内嵌在python中,并通过re ...

  3. python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

    python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess ...

  4. 常用的re模块的正则匹配的表达式

    07.01自我总结 常用的re模块的正则匹配的表达式 一.校验数字的表达式 1.数字 ^[0-9]\*$ 2.n位的数字 ^\d{n}$ 3.至少n位的数字 ^\d{n,}$ 4.m-n位的数字 ^\ ...

  5. python语法基础-常用模块-re模块

    ###############     re模块   ################ 正则表达式的规则: # re模块 # 正则表达式,就是做字符串匹配的,在re模块出现之前就有这个正则表达式了,任 ...

  6. Python常用内建模块

    Python常用内建模块 datetime 处理日期和时间的标准库. 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import da ...

  7. python模块之re正则表达式

    41.python的正则表达式      1. python中re模块提供了正则表达式相关操作 字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字      \W大写代表非\w ...

  8. 转:Yii实战中8个必备常用的扩展,模块和widget

    转载自:http://www.yiiframework.com/wiki/180/yii8/ 在经过畅K网的实战后,总结一下在Yii的项目中会经常用到的组件和一些基本的使用方法,分享给大家,同时也给自 ...

  9. s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译

    时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...

随机推荐

  1. 1.future线程通信

    #include <future> #include<iostream> #include <thread> #include <thread> #in ...

  2. Android 度量单位

    单位 注释 px(像素) 每个像素对应手机上的一个点,在不同设备上1px表示的长度不一定相同 screen size(屏幕尺寸) 指手机对角线的长度,如4.7英寸 resolution(分辨率) 指屏 ...

  3. WPF Template

    ControlTemplate ControlTemplate:用于定义控件的结构和外观,这样可以将控件外观与控件功能分离开. 在xaml中ControlTemplate通常配置到Style中,通过S ...

  4. Java文件(io)编程——文件字符流的使用

    案例1: 读取一个文件并写入到另一个文件中,char[] 来中转. 首先要在E盘下创建一个文本文档,命名为test.txt,输入一些字符串. public class Demo_5 { public ...

  5. 【BZOJ4016】【FJOI2014】最短路径树问题

    题意: Description 给一个包含n个点,m条边的无向连通图.从顶点1出发,往其余所有点分别走一次并返回. 往某一个点走时,选择总长度最短的路径走.若有多条长度最短的路径,则选择经过的顶点序列 ...

  6. luogu P1592 互质(欧拉函数)

    题意 (n<=106,k<=108) 题解 一开始以为是搜索. 但想想不对,翻了一眼题解发现是欧拉函数. 因为 gcd(a,b)=gcd(a,a+b) 所以和n互质的数应该是类似a1,a2 ...

  7. python购物车系统

    购物车系统模拟:product_list = [ ('java',100), ('python',200), ('键盘',500), ('电脑',4000), ('mac Book',7000),]S ...

  8. 洛谷 P3914 染色计数

    P3914 染色计数 题目描述 有一颗NN个节点的树,节点用1,2,\cdots,N1,2,⋯,N编号.你要给它染色,使得相邻节点的颜色不同.有MM种颜色,用1,2,\cdots,M1,2,⋯,M编号 ...

  9. Qt资料大全

    简述 发福利了.发福利了.发福利了,重要的事情说三遍... 为了方便更多Qter了解.学习Qt,现将相关资源进行整理,主要内容包括:Qt官网.编码风格.GitHub & Third-Party ...

  10. OKHttp使用简单介绍

    如今android网络方面的第三方库非常多,volley.Retrofit.OKHttp等,各有各自的特点,这边博客就来简介下怎样使用OKHttp. 梗概 OKHttp是一款高效的HTTP客户端,支持 ...