清风竹林

ぷ雪飘绛梅映残红
   ぷ花舞霜飞映苍松
     ----- Do more,suffer less

Python Challenge lv3: re

  题目链接: http://www.pythonchallenge.com/pc/def/equality.html

  One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.  何为big bodyguards? 我估计是大写字母,即要求找到由三个大写字母包围着的小写字母。事实上,题目要求的确如此。不过我在一开始的时候走了弯路:我把连续的七个字母全部都打印出来了(左边三个大写字母,中间一个小写字母,右边三个大写字母),费了半天才搞明白原来要求的只是中间的小写字母。
  另外注意EXACTLY 这个词,即“当且仅当”左右两边均为“三”个大写字母的pattern才算。

  代码到也简单:

import re

if __name__ == '__main__':    
    finpath 
= 'fin.txt'
    with open(finpath) as fin:
        
# translate text into a single string
        text = ''.join([line.rstrip() for line in fin.read()])
        pattern 
= re.compile(r'[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]')
        
print(''.join(pattern.findall(text)))

程序输出:linkedlist

参考答案

posted on 2009-05-11 15:52 李现民 阅读(544) 评论(0)  编辑 收藏 引用 所属分类: python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理