pyhton学习笔记

雾!

python 是一门面向对象的脚本语言,其语法类似于英语语法的特性受很多人喜欢,简洁的编码风格不像java需要多行的代码申明。(片面之谈)

清明节假期的漫长时间,窝在寝室中,看着Python的教学视频,枯燥乏味,故而牛刀小试网络爬虫,有记得过年时期在知乎上有看到基于python的微信自动回复拜年问好,做了个自动回复糗事百科上小笑话的小脚本。

python 的类属性是定义在init方法里的,在类里调用 self.属性
类方法 里的第一个参数 为 对象自身。

对于函数里的变量,用global 修饰可以使其扩展作用域为全局变量。


# *-*  coding:UTF-8  *-*

import itchat, time, re
from itchat.content import *

import urllib,re
from urllib.request import Request,urlopen,URLError

class WechatContent:
    def __init__(self):
        self.stories=[]  #存放段子
        self.pageIndex = 1
        self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        self.headers={ 'User-Agent' : self.user_agent}  #初始化headers
        self.enable=True  #程序是否运行的变量
    
    #获取网页内容
    def getWebPage(self):
        url="http://www.qiushibaike.com/hot.page"+str(self.pageIndex)
        request=Request(url,headers=self.headers)
        try:
            response=urlopen(request)
            #print(response.read())
            return response.read().decode('utf-8')  #将页面转为utf-8
        except URLError as e:
            if hasattr(e,'reason'):
                print(u"连接错误",e.reason)
                return None

    #获取段子
    def getContent(self):
        content=self.getWebPage()
        if not content:
            return 0;
        else:
            pattern=re.compile('<div class="content">\s*<span>\s*(\S*?)\s*</span>\s*</div>',re.S)
            items=re.findall(pattern,content)
            for item in items:
                item.replace("\s*","")
                self.stories.append(item)

    #发送段子
    def postContent(self):
        story=self.stories.pop() 
        #print (story)
        return story
     
    def start(self):
       if  not self.stories:
           self.pageIndex+=1
           self.getContent()

wc=WechatContent()
wc.start()
#print(wc.postContent())

priortext='hello world'

@itchat.msg_register([TEXT])
def text_reply(msg):
    if not wc.postContent():
        wc.start()
    
    text=wc.postContent()
    friend=itchat.search_friends(userName=msg['FromUserName'])
    print(friend['RemarkName'])
    print(msg['Text'])
    print("回复:\t",text)
    itchat.send(text ,msg['FromUserName'])

@itchat.msg_register([PICTURE, RECORDING, VIDEO, SHARING])
def other_reply(msg):
    itchat.send(priortext, msg['FromUserName'])

itchat.auto_login(enableCmdQR=True,hotReload=True)
itchat.run()

哈哈,自动回复中我后来加了,收到消息中有“什么”字样时,回复“我给找的段子搞笑吧,哈哈”,然后朋友以为我给他找了好多段子。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 教程总纲:http://www.runoob.com/python/python-tutorial.html 进阶...
    健康哥哥阅读 2,077评论 1 3
  • 要点: 函数式编程:注意不是“函数编程”,多了一个“式” 模块:如何使用模块 面向对象编程:面向对象的概念、属性、...
    victorsungo阅读 1,587评论 0 6
  • 有java基础,要做运维,想学python,求推荐python书籍? 知乎链接:https://www.zhihu...
    时修七年阅读 1,734评论 0 12
  • 今天下午学校举行了“做合格教师,做社会尊重的教师”报告会,我们班有幸选了一名家长和一名学生作为代表发言,在这其中也...
    强丽阅读 275评论 0 5
  • 1、综述 1.1 什么是心悦俱乐部 心悦俱乐部是腾讯互动娱乐旗下的一个服务于高端玩家的会员体系。按照成员在前365...
    xusongqi阅读 2,954评论 0 49