在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中SQLAlchemy排序的一个坑
Feb 24 Python
运动检测ViBe算法python实现代码
Jan 09 Python
pandas系列之DataFrame 行列数据筛选实例
Apr 12 Python
解决Python pandas plot输出图形中显示中文乱码问题
Dec 12 Python
python用fsolve、leastsq对非线性方程组求解
Dec 15 Python
python url 参数修改方法
Dec 26 Python
OpenCV-Python 摄像头实时检测人脸代码实例
Apr 30 Python
Python面向对象封装操作案例详解 II
Jan 02 Python
python实现猜拳游戏
Mar 04 Python
python实现微信打飞机游戏
Mar 24 Python
解决Django中checkbox复选框的传值问题
Mar 31 Python
python读写数据读写csv文件(pandas用法)
Dec 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 substr 截取字符串出现乱码问题解决方法[utf8与gb2312]
2011/12/16 PHP
推荐25款php中非常有用的类库
2014/09/29 PHP
PHP采用get获取url汉字出现乱码的解决方法
2014/11/13 PHP
PHP使用memcache缓存技术提高响应速度的方法
2014/12/26 PHP
自制PHP框架之模型与数据库
2017/05/07 PHP
javascript Split方法,indexOf方法、lastIndexOf 方法和substring 方法
2009/03/21 Javascript
jQuery aminate方法定位到页面具体位置
2013/12/26 Javascript
Javascript中封装window.open解决不兼容问题
2014/09/28 Javascript
jquery——九宫格大转盘抽奖实例
2017/01/16 Javascript
JS实现DOM节点插入操作之子节点与兄弟节点插入操作示例
2018/07/30 Javascript
Django+Vue实现WebSocket连接的示例代码
2019/05/28 Javascript
selenium+java中用js来完成日期的修改
2019/10/31 Javascript
浅析VUE防抖与节流
2020/11/24 Vue.js
可拖拽组件slider.js使用方法详解
2020/12/04 Javascript
Python 执行字符串表达式函数(eval exec execfile)
2014/08/11 Python
python显示生日是星期几的方法
2015/05/27 Python
使用python加密自己的密码
2015/08/04 Python
Python实现的文本编辑器功能示例
2017/06/30 Python
Python cookbook(数据结构与算法)在字典中将键映射到多个值上的方法
2018/02/18 Python
PyQt5每天必学之工具提示功能
2018/04/19 Python
对TensorFlow的assign赋值用法详解
2018/07/30 Python
Python反射和内置方法重写操作详解
2018/08/27 Python
漂亮的Django Markdown富文本app插件的实现
2019/01/02 Python
Python创建一个元素都为0的列表实例
2019/11/28 Python
python 初始化一个定长的数组实例
2019/12/02 Python
详解有关PyCharm安装库失败的问题的解决方法
2020/02/02 Python
python实现sm2和sm4国密(国家商用密码)算法的示例
2020/09/26 Python
Python3利用scapy局域网实现自动多线程arp扫描功能
2021/01/21 Python
个性化皮包、小袋、生活配件:Mon Purse
2019/03/26 全球购物
司机岗位职责
2013/11/15 职场文书
师德师风个人反思
2014/04/28 职场文书
企业爱心捐款倡议书
2015/04/27 职场文书
预备党员考察意见范文
2015/06/01 职场文书
教师培训简讯
2015/07/20 职场文书
阿里云Nginx配置https实现域名访问项目(图文教程)
2021/03/31 Servers
python tqdm用法及实例详解
2021/06/16 Python