zoukankan      html  css  js  c++  java
  • Python Challenge 2

    http://www.pythonchallenge.com/pc/def/ocr.html

    提示看源文件,一大堆字符,说要找到出现次数最少的字符,

    使用字符串的count方法可以做到,首先想到的办法是把那堆字符串保存到文本文档里面

    通过读取文本文档来使用count方法判断出现次数少于10次的字符

    >>> text = open('data.txt','r').read()
    >>> for a in text:
    	l=text.count(a)
    	if l<10:
    		print a,':',l
    
    		
    e : 1
    q : 1
    u : 1
    a : 1
    l : 1
    i : 1
    t : 1
    y : 1

    得到下一关的地址

    http://www.pythonchallenge.com/pc/def/equality.html

    另外一个简单的方法 直接使用urllib获取页面源代码 使用正则表达式来提取需要的字段

    针对例子说的 提取前后都为非字母 中间一个是字母的所有元素 即可得到答案 有点幸运的成分在里面

    #coding:utf-8
    
    import urllib,re
    
    # 获取HTML源代码
    ocr = urllib.urlopen\
    ('http://www.pythonchallenge.com/pc/def/ocr.html').read()
    
    # 查找[a-z]范围的2边有5个非字幕的情况
    pat = re.compile(r"[^a-z]{5}([a-z])[^a-z]{5}")
    
    print ''.join(re.findall(pat,text))
    

    之前写的确实有点撞大运的色彩...评论的很中肯... 做了下改进 这样解这个题目算是比较靠谱的办法了

    >>> import re
    >>> import urllib
    >>> ocr = urllib.urlopen(
    'http://www.pythonchallenge.com/pc/def/ocr.html').read()
    
    # 匹配注释中的内容
    # re.S 匹配任意字符包括换行符
    # .*? 加?避免贪婪模式 尽量少的匹配
    >>> data = re.findall(r'<!--(.*?)-->',ocr,re.S)
    # 剔除说明注释
    >>> data = data[1] 
    >>> for i in set(data):
    	print i,':',data.count(i)
    	
    
    : 1221
    ! : 6079
    # : 6115
    % : 6104
    $ : 6046
    & : 6043
    ) : 6186
    ( : 6154
    + : 6066
    * : 6034
    @ : 6157
    [ : 6108
    ] : 6152
    _ : 6112
    ^ : 6030
    a : 1
    e : 1
    i : 1
    l : 1
    q : 1
    u : 1
    t : 1
    y : 1
    { : 6046
    } : 6105
    
    # 得到最少的字符是'aeilquty' 
    # 现在需要按照他们在字符串中出现的位置进行下排序
    >>> for i in data:
    	if i in 'aeilquty': print i,
    
    	
    e q u a l i t y
    
    # 得到下一关的地址
    
  • 相关阅读:
    Linux常用
    Netty实战八之引导
    Netty实战九之单元测试
    Netty实战七之EventLoop和线程模型
    作为团队技术负责人,我是这样面试前端的
    Netty实战六之ChannelHandler和ChannelPipeline
    Netty实战五之ByteBuf
    Netty实战四之传输
    Netty实战三之Netty的组件和设计
    Netty实战二之自己的Netty应用程序
  • 原文地址:https://www.cnblogs.com/pylemon/p/2029489.html
Copyright © 2011-2022 走看看