在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实现的可以拷贝或剪切一个文件列表中的所有文件
Apr 30 Python
用Python编写一个简单的俄罗斯方块游戏的教程
Apr 03 Python
Python使用设计模式中的责任链模式与迭代器模式的示例
Mar 02 Python
Python按行读取文件的简单实现方法
Jun 22 Python
Python实现遍历目录的方法【测试可用】
Mar 22 Python
基于python中的TCP及UDP(详解)
Nov 06 Python
python读取txt文件并取其某一列数据的示例
Feb 19 Python
python绘制封闭多边形教程
Feb 18 Python
python 截取XML中bndbox的坐标中的图像,另存为jpg的实例
Mar 10 Python
Python matplotlib 绘制双Y轴曲线图的示例代码
Jun 12 Python
Python实现中英文全文搜索的示例
Dec 04 Python
Python中生成随机数据安全性、多功能性、用途和速度方面进行比较
Apr 14 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 正则匹配函数体
2009/08/25 PHP
php 魔术函数使用说明
2010/02/21 PHP
php注销代码(session注销)
2012/05/31 PHP
Laravel框架集成UEditor编辑器的方法图文与实例详解
2019/04/17 PHP
通过event对象的fromElement属性解决热区设置主实体的一个bug
2008/12/22 Javascript
ext 同步和异步示例代码
2009/09/18 Javascript
JS获得选取checkbox整行数据的方法
2015/01/28 Javascript
JavaScript中数组的合并以及排序实现示例
2015/10/24 Javascript
js实现微信分享代码
2020/10/11 Javascript
vue.js 上传图片实例代码
2017/06/22 Javascript
JavaScript实现音乐自动切换和轮播
2017/11/05 Javascript
React native ListView 增加顶部下拉刷新和底下点击刷新示例
2018/04/27 Javascript
CentOS7中源码编译安装NodeJS的完整步骤
2018/10/13 NodeJs
Vue项目中使用better-scroll实现一个轮播图自动播放功能
2018/12/03 Javascript
js module大战
2019/04/19 Javascript
Node 搭建一个静态资源服务器的实现
2019/05/20 Javascript
Vue.js下拉菜单组件使用方法详解
2019/10/19 Javascript
查找Vue中下标的操作(some和findindex)
2020/08/12 Javascript
Python每天必学之bytes字节
2016/01/28 Python
深入浅析python中的多进程、多线程、协程
2016/06/22 Python
Python 获得命令行参数的方法(推荐)
2018/01/24 Python
Python通过调用有道翻译api实现翻译功能示例
2018/07/19 Python
Python实现iOS自动化打包详解步骤
2018/10/03 Python
Python学习笔记之抓取某只基金历史净值数据实战案例
2019/06/03 Python
Django model select的多种用法详解
2019/07/16 Python
python使用tomorrow实现多线程的例子
2019/07/20 Python
Python openpyxl模块实现excel读写操作
2020/06/30 Python
jupyter 添加不同内核的操作
2021/02/06 Python
美国杂志订阅折扣与优惠网站:Magazines.com
2016/08/31 全球购物
手工制作的男士奢华英国鞋和服装之家:Goodwin Smith
2019/06/21 全球购物
最新的大学生找工作自我评价
2013/09/29 职场文书
护理学应聘自荐书范文
2014/02/05 职场文书
倡议书的写法
2014/08/30 职场文书
开展党的群众路线教育实践活动总结报告
2014/10/31 职场文书
道歉信怎么写
2015/05/12 职场文书
给领导敬酒词
2015/08/12 职场文书