在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单链表的简单实现方法
Sep 23 Python
Python实现去除代码前行号的方法
Mar 10 Python
python数据处理实战(必看篇)
Jun 11 Python
PyCharm 常用快捷键和设置方法
Dec 20 Python
Python实现接受任意个数参数的函数方法
Apr 21 Python
Python使用paramiko操作linux的方法讲解
Feb 25 Python
Python操作rabbitMQ的示例代码
Mar 19 Python
详解Python的三种可变参数
May 08 Python
python pandas时序处理相关功能详解
Jul 03 Python
python 队列基本定义与使用方法【初始化、赋值、判断等】
Oct 24 Python
Python调用Windows API函数编写录音机和音乐播放器功能
Jan 05 Python
Python任务调度模块APScheduler使用
Apr 15 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接收POST数据方式
2015/06/05 PHP
PHP读取大文件的多种方法介绍
2016/04/04 PHP
javaScript 读取和设置文档元素的样式属性
2009/04/14 Javascript
js 未结束的字符串常量错误解决方法
2010/06/13 Javascript
Extjs中使用extend(js继承) 的代码
2012/03/15 Javascript
JavaScript中的eval()函数详解
2013/08/22 Javascript
node.js中的fs.fchownSync方法使用说明
2014/12/16 Javascript
angularjs创建弹出框实现拖动效果
2020/08/25 Javascript
JS实现刷新父页面不弹出提示框的方法
2016/06/22 Javascript
关于vue.js v-bind 的一些理解和思考
2017/06/06 Javascript
jQuery Ajax实现Select多级关联动态绑定数据的实例代码
2018/10/26 jQuery
JS中实现浅拷贝和深拷贝的代码详解
2019/06/05 Javascript
Vue实现简单计算器案例
2020/02/25 Javascript
vue计算属性+vue中class与style绑定(推荐)
2020/03/30 Javascript
[01:21]DOTA2 新英雄 森海飞霞
2020/12/18 DOTA
Python ValueError: invalid literal for int() with base 10 实用解决方法
2015/06/21 Python
Python实现树的先序、中序、后序排序算法示例
2017/06/23 Python
让Django支持Sql Server作后端数据库的方法
2018/05/29 Python
python 解决动态的定义变量名,并给其赋值的方法(大数据处理)
2018/11/10 Python
Apache,wsgi,django 程序部署配置方法详解
2019/07/01 Python
对python中的os.getpid()和os.fork()函数详解
2019/08/08 Python
python银行系统实现源码
2019/10/25 Python
Python在终端通过pip安装好包以后在Pycharm中依然无法使用的问题(三种解决方案)
2020/03/10 Python
Eclipse配置python默认头过程图解
2020/04/26 Python
keras 自定义loss model.add_loss的使用详解
2020/06/22 Python
PyCharm2019.3永久激活破解详细图文教程,亲测可用(不定期更新)
2020/10/29 Python
HTML5给汉字加拼音收起展开组件的实现代码
2020/04/08 HTML / CSS
应聘自荐信
2013/12/14 职场文书
九一八事变演讲稿
2014/09/05 职场文书
关于安全的广播稿
2014/10/23 职场文书
党员群众路线整改措施及今后努力方向
2014/10/28 职场文书
2014年企业党支部工作总结
2014/12/04 职场文书
2015年医德医风工作总结
2015/04/02 职场文书
Python Pycharm虚拟下百度飞浆PaddleX安装报错问题及处理方法(亲测100%有效)
2021/05/24 Python
详解如何用Python实现感知器算法
2021/06/18 Python
JavaScript前端面试组合函数
2022/06/21 Javascript