免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2462 | 回复: 7
打印 上一主题 下一主题

How would you do the equivalent in Python? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-03-26 05:15 |只看该作者 |倒序浏览
In perl, below code snippet can print out the data between BEGIN ~ END from a text file.

while(<IN> {
     print if (/#BEGIN/oi .. /#END/oi);
  }

I wonder : How would you do the equivalent in Python? Thank you in advance !!!

BTW: the perl code at least runs V5.8.8

论坛徽章:
0
2 [报告]
发表于 2011-03-26 13:09 |只看该作者
本帖最后由 llbgurs 于 2011-03-26 13:19 编辑

try this:
  1. import re

  2. f =open("data")
  3. pat = re.compile(r"#BEGIN(.*?)#END", re.I)

  4. for line in f:
  5.     match_obj = re.search(pat, line)
  6.     if match_obj is not None:
  7.         print match_obj.group(1)

复制代码

论坛徽章:
0
3 [报告]
发表于 2011-03-26 21:46 |只看该作者
回复 2# llbgurs

Given data file as follows:

# start data test file

#BEGIN
line 1
line 2
line 3
line 4
line 5
#END

# end of data test file

then kicked off your script, it didn't output anything matched. I'm new to python, think your pattern looks ok from the point of my perl view, I guess that you forgot to turn on multiple line mode, is it ? anyway, thank you very much for your kind and quick reply.

论坛徽章:
0
4 [报告]
发表于 2011-03-26 23:33 |只看该作者

  1. import sys, itertools
  2. sys.stdout.writelines(itertools.takewhile('#END\n'.__ne__,itertools.dropwhile('#BEGIN\n'.__ne__, sys.stdin)))
复制代码

论坛徽章:
0
5 [报告]
发表于 2011-03-26 23:36 |只看该作者
  1. import re

  2. f =open("data")
  3. pat = re.compile(r"#BEGIN(.*?)#END", re.I|re.S)

  4. text = f.read()

  5. match_obj = pat.search(text)
  6. if match_obj is not None:
  7.         print match_obj.group()

  8. f.close()
复制代码
This should be work, if no require to print #BEGIN and $END

try print match_obj.group(1)

论坛徽章:
0
6 [报告]
发表于 2011-03-27 01:50 |只看该作者
回复 5# llbgurs


    It is a perfect solution !!! Thanks a lot !!!

论坛徽章:
0
7 [报告]
发表于 2011-03-27 01:58 |只看该作者
Kabie 发表于 2011-03-26 23:33



    It looks coolest ! although it printed out below
---------------
#BEGIN
line 1
........
line 5
---------------
    It seemed not print out #END  -- it is a bug ? could you take care of it ? thank you so much !!!

论坛徽章:
0
8 [报告]
发表于 2011-03-27 08:10 |只看该作者
I guess you have to print '#END' manually afterwards...
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP