在python中使用正则表达式查找可嵌套字符串组


Posted in Python onOctober 24, 2017

在网上看到一个小需求,需要用正则表达式来处理。原需求如下:

找出文本中包含”因为……所以”的句子,并以两个词为中心对齐输出前后3个字,中间全输出,如果“因为”和“所以”中间还存在“因为”“所以”,也要找出来,另算一行,输出格式为:

行号 前面3个字 *因为* 全部 &所以& 后面3个字(标点符号算一个字)

2 还不是 *因为* 这里好, &所以& 没有人

实现方法如下:

#encoding:utf-8
import os
import re
def getPairStriList(filename):
  pairStrList = []
  textFile = open(filename, 'r')
  pattern = re.compile(u'.{3}\u56e0\u4e3a.*\u6240\u4ee5.{3}') #u'\u56e0\u4e3a和u'\u6240\u4ee5'分别为“因为”和“所以”的utf8码
  for line in textFile:
    utfLine = line.decode('utf8')
    result = pattern.search(utfLine)
    while result:
      resultStr = result.group()
      pairStrList.append(resultStr)
      result = pattern.search(resultStr,2,len(resultStr)-2)
  #对每个字符串进行格式转换和拼接  
  for i in range(len(pairStrList)):
    pairStrList[i] = pairStrList[i][:3] + pairStrList[i][3:5].replace(u'\u56e0\u4e3a',u' *\u56e0\u4e3a* ',1) + pairStrList[i][5:]
    pairStrList[i] = pairStrList[i][:len(pairStrList[i])-5] + pairStrList[i][len(pairStrList[i])-5:].replace(u'\u6240\u4ee5',u' &\u6240\u4ee5& ',1)
    pairStrList[i] = str(i+1) + ' ' + pairStrList[i]
  return pairStrList
  if __name__ == '__main__':
  pairStrList = getPairStriList('test.txt')
  for str in pairStrList:
    print str

PS:下面看下python里使用正则表达式的组嵌套

由于组本身是一个完整的正则表达式,所以可以将组嵌套在其他组中,以构建更复杂的表达式。下面的例子,就是进行组嵌套的例子:

#python 3.6 
#蔡军生  
#http://blog.csdn.net/caimouse/article/details/51749579 
# 
import re 
def test_patterns(text, patterns): 
  """Given source text and a list of patterns, look for 
  matches for each pattern within the text and print 
  them to stdout. 
  """ 
  # Look for each pattern in the text and print the results 
  for pattern, desc in patterns: 
    print('{!r} ({})\n'.format(pattern, desc)) 
    print(' {!r}'.format(text)) 
    for match in re.finditer(pattern, text): 
      s = match.start() 
      e = match.end() 
      prefix = ' ' * (s) 
      print( 
        ' {}{!r}{} '.format(prefix, 
                   text[s:e], 
                   ' ' * (len(text) - e)), 
        end=' ', 
      ) 
      print(match.groups()) 
      if match.groupdict(): 
        print('{}{}'.format( 
          ' ' * (len(text) - s), 
          match.groupdict()), 
        ) 
    print() 
  return

例子:

#python 3.6 
#蔡军生  
#http://blog.csdn.net/caimouse/article/details/51749579 
# 
from re_test_patterns_groups import test_patterns 
test_patterns( 
  'abbaabbba', 
  [(r'a((a*)(b*))', 'a followed by 0-n a and 0-n b')], 
)

结果输出如下:

'a((a*)(b*))' (a followed by 0-n a and 0-n b)
 'abbaabbba'
 'abb'    ('bb', '', 'bb')
   'aabbb'  ('abbb', 'a', 'bbb')
     'a' ('', '', '')

总结

以上所述是小编给大家介绍的在python中使用正则表达式查找可嵌套字符串组,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python实现字符串和日期相互转换的方法
May 13 Python
python利用urllib实现爬取京东网站商品图片的爬虫实例
Aug 24 Python
matplotlib subplots 设置总图的标题方法
May 25 Python
python 实现读取一个excel多个sheet表并合并的方法
Feb 12 Python
Python2与Python3的区别实例总结
Apr 17 Python
OpenCV中VideoCapture类的使用详解
Feb 14 Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
Feb 19 Python
Python接口开发实现步骤详解
Apr 26 Python
Python爬虫之Selenium鼠标事件的实现
Dec 04 Python
Python3 用matplotlib绘制sigmoid函数的案例
Dec 11 Python
Django实现翻页的示例代码
May 24 Python
python实现学员管理系统(面向对象版)
Jun 05 Python
python爬虫之BeautifulSoup 使用select方法详解
Oct 23 #Python
浅谈python中copy和deepcopy中的区别
Oct 23 #Python
python的构建工具setup.py的方法使用示例
Oct 23 #Python
python使用pyqt写带界面工具的示例代码
Oct 23 #Python
基于Django的python验证码(实例讲解)
Oct 23 #Python
itchat接口使用示例
Oct 23 #Python
python实现微信接口(itchat)详细介绍
Oct 23 #Python
You might like
php获取访问者IP地址汇总
2015/04/24 PHP
Yii隐藏URL中index.php的方法
2016/07/12 PHP
老生常谈PHP数组函数array_merge(必看篇)
2017/05/25 PHP
正则表达式中特殊符号及正则表达式的几种方法总结(replace,test,search)
2013/11/26 Javascript
javascript简单实现表格行间隔显示颜色并高亮显示
2013/11/29 Javascript
For循环中分号隔开的3部分的执行顺序探讨
2014/05/27 Javascript
nodejs中实现路由功能
2014/12/29 NodeJs
JavaScript数据类型判定的总结笔记
2015/07/31 Javascript
vue音乐播放器插件vue-aplayer的配置及其使用实例详解
2017/07/10 Javascript
IScroll那些事_当内容不足时下拉刷新的解决方法
2017/07/18 Javascript
jQuery实现IE输入框完成placeholder标签功能的方法
2017/09/20 jQuery
详解AngularJS之$window窗口对象
2018/01/17 Javascript
vue引入新版 vue-awesome-swiper插件填坑问题
2018/01/25 Javascript
详解关于Vuex的action传入多个参数的问题
2019/02/22 Javascript
JavaScript多种页面刷新方法小结
2019/04/04 Javascript
微信小程序实现搜索功能并跳转搜索结果页面
2019/05/18 Javascript
javascript异步处理与Jquery deferred对象用法总结
2019/06/04 jQuery
Vue最新防抖方案(必看篇)
2019/10/30 Javascript
js+canvas实现刮刮奖功能
2020/09/13 Javascript
[02:15]2014DOTA2国际邀请赛 赛后退役选手回顾
2014/08/01 DOTA
Python中将字典转换为XML以及相关的命名空间解析
2015/10/15 Python
Python3实现爬取指定百度贴吧页面并保存页面数据生成本地文档的方法
2018/04/22 Python
Python学习笔记之open()函数打开文件路径报错问题
2018/04/28 Python
Python常用的json标准库
2019/02/19 Python
python解析yaml文件过程详解
2019/08/30 Python
Python 实现opencv所使用的图片格式与 base64 转换
2020/01/09 Python
用 Python 制作地球仪的方法
2020/04/24 Python
python实现爱奇艺登陆密码RSA加密的方法示例详解
2020/05/27 Python
利用三角函数在canvas上画虚线的方法
2018/01/11 HTML / CSS
大学系主任推荐信范文
2013/12/24 职场文书
开学典礼感言
2014/02/16 职场文书
机械专业求职信
2014/05/25 职场文书
出纳工作检讨书范文
2014/12/27 职场文书
2015年秋季新学期寄语
2015/03/25 职场文书
餐饮店长岗位职责
2015/04/14 职场文书
创业计划书之校园跑腿公司
2019/09/24 职场文书