加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

教案生成器(.doc格式)

发布时间:2020-12-17 17:16:26 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 # -*- coding:utf-8 -*-import datetime #,calendarfrom copy import deepcopyfrom BeautifulSoup import BeautifulSoup#~ from pyquery import PyQue

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

# -*- coding:utf-8 -*-

import datetime  #,calendar
from copy import deepcopy
from BeautifulSoup import BeautifulSoup
#~ from pyquery import PyQuery as pq
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


class Util(object):
    """
    教案生成器,自动填写表头,产生 .doc 格式文档
    """
    @classmethod
    def read_config(cls):
        """ 通过配置文件获取课程配置 """
        conf = None
        input_config = sys.argv[1] if len(sys.argv) > 1 else "conf.xml"
        with open(input_config,'rb') as conf_file:
            soup = BeautifulSoup(conf_file.read(),fromEncoding="gbk")
            conf = {'class': soup.find('class').text.strip(),'lesson': soup.find('lesson').text.strip(),'book': soup.find('book').text.strip(),'press': soup.find('press').text.strip(),'term': soup.find('term').text.strip(),'year': soup.find('year').text.strip(),'begin': soup.find('begin').text.strip(),'weeks': int(soup.find('weeks').text),'holiday': soup.find('holiday').text.strip(),}
            conf['holidays'] = [x.split(':') for x in conf['holiday'].split(',')]

            # 日期条件检查器
            always = lambda x: True
            odd = lambda x: x % 2 == 1  # 单周
            even = lambda x: x % 2 == 0
            schedule = {}
            for week in soup.findAll('week'):
                func = always
                if 'select' in week:
                    func = odd if odd(int(week['select'])) else even
                schedule[int(week['n'])] = [func,week.text]
                #~ {5:[f,'5,6'],3:[f,'3,4'],1:[f,'1,2'],6:[fo,6']}
            conf['schedule'] = schedule
            #~ print schedule.keys()
        return conf

    @classmethod
    def holiday(cls,day,holidays):
        """ 判断是否节假日 """
        for hd in holidays:
            begin = hd[0]
            span = int(hd[1]) if len(hd) > 1 else 1
            hdt = datetime.datetime.strptime(begin,"%Y-%m-%d")
            if 0 < (day - hdt).days + 1 <= span:
                return True
        return False

    @classmethod
    def date_list(cls,begin_time,end_time,schedule):
        """ 获取工作日列表 """
        oneday = datetime.timedelta(days=1)
        day_time = begin_time
        work_weeks = schedule.keys()
        while day_time <= end_time:
            for it in work_weeks:
                week = day_time.weekday() + 1
                if week <= it:
                    day_time += datetime.timedelta(it - week)
                    week_ith = (day_time - begin_time).days / 7 + 1
                    #~ print 'week_th:',week_ith
                    #~ print day_time.strftime('%A,%Y-%m-%d')
                    #~ print "lessons:",schedule[it][1:]
                    # 日期条件检查
                    if schedule[it][0](week_ith):
                        yield day_time
            day_time += oneday

    @classmethod
    def run(cls):
        """ 生成教案 """
        conf = cls.read_config()
        with open("templet.dat",'rb') as temp_file:
            # read templet and generate
            soup = BeautifulSoup(temp_file.read(),fromEncoding="gbk")

            blank = soup.body.brTag # 指定Tag后缀写法
            page = soup.body.div
            page.find('span',{"name": "class"}).string = conf['class']
            page.find('span',{"name": "lesson"}).string = conf['lesson']
            page.find('span',{"name": "book"}).string = conf['book']
            page.find('span',{"name": "press"}).string = conf['press']
            page.find('span',{"name": "term"}).string = conf['term']
            page.find('span',{"name": "year_range"}).string = conf['year']

            begin_time = datetime.datetime.strptime(conf['begin'],"%Y-%m-%d")
            end_time = begin_time + datetime.timedelta(days=conf['weeks']*7)
            schedule = conf['schedule']
            work_days = cls.date_list(begin_time,schedule)
            for i,date in enumerate(work_days):
                if cls.holiday(date,conf['holidays']):
                    print '-- skip holiday:',date.strftime('%Y-%m-%d')
                    continue
                week = date.weekday() + 1
                week_ith = (date - begin_time).days / 7 + 1
                print "##",date.strftime('%Y-%m-%d'),'%s%s' % ("星期",CN_NUM[week]),"第",week_ith,"周"
                page.find('span',{"name": "page_ith"}).string = str(i+1)
                page.find('span',{"name": "week_ith"}).string = str(week_ith)
                page.find('span',{"name": "lesson_ith"}).string = schedule[week][1]
                page.find('span',{"name": "week"}).string = '%s%s' % ("星期",CN_NUM[week])
                page.find('span',{"name": "year"}).string = str(date.year)
                page.find('span',{"name": "month"}).string = '%02d' % date.month
                page.find('span',{"name": "day"}).string = '%02d' % date.day

                # 复制页面元素需要深拷贝,否则为移动元素
                # 不能直接 insert str(page),因为 BS 会对其中 html 特殊字符转义
                page = deepcopy(page)
                soup.body.insert(len(soup.body),page)
                blank = deepcopy(blank)
                soup.body.insert(len(soup.body),blank)

            year_span = conf['year'].split()
            # 长行字符串写法
            out_file_name = ''.join((year_span[0],'-',year_span[-1],conf['term'],'《' + conf['lesson'] + '》','教案-教师','.doc'))
            with open(out_file_name,'wb') as out_file:
                out_file.write(str(soup))

if __name__ == '__main__':
    CN_NUM = {
        0: '零',1: '一',2: '二',3: '三',4: '四',5: '五',6: '六',7: '七',8: '八',9: '九',}
    Util.run()

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读