在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获取糗百图片代码实例
Dec 18 Python
python脚本替换指定行实现步骤
Jul 11 Python
Python学习笔记之if语句的使用示例
Oct 23 Python
Python实现嵌套列表及字典并按某一元素去重复功能示例
Nov 30 Python
Django Rest framework三种分页方式详解
Jul 26 Python
Python实现性能自动化测试竟然如此简单
Jul 30 Python
python zip()函数使用方法解析
Oct 31 Python
基于Python获取城市近7天天气预报
Nov 26 Python
TensorFLow 变量命名空间实例
Feb 11 Python
python实现俄罗斯方块小游戏
Apr 24 Python
解决keras加入lambda层时shape的问题
Jun 11 Python
使用Python操作MySQL的小技巧
Sep 10 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中目录,文件操作详谈
2007/03/19 PHP
PHP用反撇号执行外部命令
2015/04/14 PHP
javascript针对DOM的应用分析(三)
2012/04/15 Javascript
JavaScript 定时器 SetTimeout之定时刷新窗口和关闭窗口(代码超简单)
2016/02/26 Javascript
JS实现为排序好的字符串找出重复行的方法
2016/03/02 Javascript
jQuery实现鼠标经过时高亮,同时其他同级元素变暗的效果
2016/09/18 Javascript
Angular2使用Angular-CLI快速搭建工程(二)
2017/05/21 Javascript
Nuxt.js踩坑总结分享
2018/01/18 Javascript
解决Webpack 热部署检测不到文件变化的问题
2018/02/22 Javascript
解决Vue打包之后文件路径出错的问题
2018/03/06 Javascript
深入浅析Vue中的Prop
2018/06/10 Javascript
JavaScript如何把两个数组对象合并过程解析
2019/10/10 Javascript
Python实现将目录中TXT合并成一个大TXT文件的方法
2015/07/15 Python
python多维数组切片方法
2018/04/13 Python
python3实现磁盘空间监控
2018/06/21 Python
Python构建图像分类识别器的方法
2019/01/12 Python
Python选择网卡发包及接收数据包
2019/04/04 Python
Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法示例
2019/10/17 Python
解析PyCharm Python运行权限问题
2020/01/08 Python
Python中random模块常用方法的使用教程
2020/10/04 Python
CSS书写规范、顺序和命名规则
2014/03/06 HTML / CSS
html5中svg canvas和图片之间相互转化思路代码
2014/01/24 HTML / CSS
澳大利亚设计的优质鞋类和适合澳大利亚生活方式的服装:Rivers
2019/04/23 全球购物
Trench London官方网站:高级风衣和意大利皮夹克
2020/07/11 全球购物
自荐信格式技巧有哪些呢
2013/11/19 职场文书
宣传普通话标语
2014/06/27 职场文书
党的生日活动方案
2014/08/15 职场文书
护士长2014年度工作总结
2014/11/11 职场文书
学术会议邀请函
2015/01/30 职场文书
中学感恩教育活动总结
2015/05/05 职场文书
机关工会工作总结2015
2015/05/26 职场文书
金陵十三钗观后感
2015/06/04 职场文书
超强台风观后感
2015/06/09 职场文书
无房证明样本
2015/06/17 职场文书
少先队大队委竞选口号
2015/12/25 职场文书
《金钱的魔力》教学反思
2016/02/20 职场文书