Python源码实例-核心基础应用

以下python题目源码可点击链接获取:
https://download.csdn.net/download/qq_64505944/87931937?spm=1001.2014.3001.5503
001 根据出生日期判断你的星座

sdate=[20,19,21,20,21,22,23,23,23,24,23,22]     # 星座判断列表
conts =['摩羯座','水瓶座','双鱼座','白羊座','金牛座','双子座','巨蟹座','狮子座','处女座','天秤座','天蝎座','射手座','摩羯座']
signs=['♑','♒','♓','♈','♉','♊','♋','♌','♍','♎','♏','♐','♑']

# 输入生日,输出星座
birth = input('请输入你的出生年月日,格式为:2001-02-21\n').strip(' ')
cbir=birth.split('-')    # 分割年月日到列表
cmonth=str(cbir[1])      # 提取月数据
cdate=str(cbir[2])       # 提取日数据
def sign(cmonth,cdate):  #  判断星座函数
    if int(cdate)<sdate[int(cmonth)-1]:   # 如果日数据早于对应月列表中对应的日期
        print(conts[int(cmonth)-1])       # 直接输出星座列表对应月对应的星座
        print(signs[int(cmonth)-1])       # 直接输出星座列表对应月对应的星座
    else:
        print(conts[int(cmonth)])         # 否则输出星座列表下一月对应的星座
        print(signs[int(cmonth)])         # 否则输出星座列表下一月对应的星座        
sign(cmonth,cdate)      # 调用星座判断程序

002根据出生日期判断生肖…

import math
lunar = '申酉戌亥子丑寅卯辰巳午未'
zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'
ztime = ['1936(1.24)', '1937(2.11)', '1938(1.31)', '1939(2.19)', '1940(2.08)', '1941(1.27)', '1942(2.15)', '1943(2.05)', '1944(1.25)', '1945(2.13)', '1946(2.02)', '1947(1.22)', '1948(2.10)', '1949(1.29)', '1950(2.17)', '1951(2.06)', '1952(1.27)', '1953(2.14)', '1954(2.03)', '1955(1.24)', '1956(2.12)', '1957(1.31)', '1958(2.18)', '1959(2.08)', '1960(1.28)', '1961(2.15)', '1962(2.05)', '1963(1.25)', '1964(2.13)', '1965(2.02)', '1966(1.21)', '1967(2.09)', '1968(1.30)', '1969(2.17)', '1970(2.06)', '1971(1.27)', '1972(2.15)', '1973(2.03)', '1974(1.23)', '1975(2.11)', '1976(1.31)', '1977(2.18)', '1978(2.07)', '1979(1.28)', '1980(2.16)', '1981(2.05)', '1982(1.25)', '1983(2.13)', '1984(2.2)', '1985(2.20)', '1986(2.09)', '1987(1.29)', '1988(2.17)', '1989(2.06)', '1990(1.27)', '1991(2.15)', '1992(2.04)', '1993(1.23)', '1994(2.10)', '1995(1.31)', '1996(2.19)', '1997(2.07)', '1998(1.28)', '1999(2.16)', '2000(2.05)', '2001(1.24)', '2002(2.12)', '2003(2.01)', '2004(1.22)', '2005(2.09)', '2006(1.29)', '2007(2.18)', '2008(2.07)', '2009(1.26)', '2010(2.14)', '2011(2.03)', '2012(1.23)', '2013(2.10)', '2014(2.04)', '2015(2.19)', '2016(2.08)', '2017(1.28)', '2018(2.16)', '2019(2.05)', '2020(1.25)']
mdate = ''
ral = ['鼠',1984]
shop = '100000056303'
inside = ''
birth = input('请输入你的出生年月日,格式为:2001-02-21\n')
cbir = birth.split('-')
cyear = cbir[0]
cmonth = cbir[1]
cdate = cbir[2]
for item in ztime:
    if item[:4] == cyear:
        mdate = item[4:].strip(' ').strip('(').strip(')')
ctime = str(cmonth) + str(cdate)
ndate = mdate.split('.')
smonth = ndate[0]
sdate = ndate[1]
stime = str(smonth) + str(sdate)
if int(ctime) < int(stime):
    cyear = int(cyear) - 1
rem = int(cyear) % 12
print('要查询的属相是:' + zodiac[rem] + '\n属相对应的年份是:' + lunar[rem] + '年')

003 使用Python制作简易数字累加器….

# -*- coding:utf-8 -*-
import os  # 导入系统功能模块
from win32com.client import Dispatch, DispatchEx  # 导入pywin32模块的client包下的函数
from win32com.client import constants  #  导入pywin32模块的client包下的保存COM常量的类
from win32com.client import gencache    #  导入pywin32模块的client包下的gencache函数
import re  # 导入正则表达式模块

import sys, codecs   # 导入标准模块
from PyPDF2 import PdfFileReader, PdfFileMerger   # 导入第三方模块PyPDF2

'''
   合并pdf文件,输出的pdf文件按输入的pdf文件名生成书签
'''
def mergefiles(path, output_filename, import_bookmarks=False):
    ''' 遍历目录下的所有pdf将其合并输出到一个pdf文件中, # 返回数字(将按该数字排序)输出的pdf文件默认带书签,
    书签名为之前的文件名。默认情况下原始文件的书签不会导入,使用import_bookmarks=True可以将原文件所带的书签也
    导入到输出的PDF文件中
    '''
    merger = PdfFileMerger() # 创建PDF合并对象
    filelist = getfilenames(filepath=path,filelist_out=[], file_ext='.pdf')  # 获取要合并的PDF文件
    if len(filelist) == 0:  # 判断是否存在要合并的文件
        print("当前目录及子目录下不存在pdf文件")
        sys.exit()  # 退出文件系统
    for filename in filelist:  # 遍历文件列表
        f = codecs.open(filename, 'rb') # 使用codecs的open()方法打开文件时,会自动转换为内部Unicode编码
        file_rd = PdfFileReader(f)
        short_filename = os.path.basename(os.path.splitext(filename)[0]) # 获取文件名称(不包括文件路径)
        if file_rd.isEncrypted == True:
            print('不支持的加密文件:%s'%(filename))
            continue
        merger.append(file_rd, bookmark=short_filename, import_bookmarks=import_bookmarks)
        f.close()  # 关闭文件对象
    out_filename=os.path.join(os.path.abspath(path), output_filename)  # 将文件名和路径连接为一个完整路径
    merger.write(out_filename) # 写入内容
    merger.close()  # 关闭PDF合并对象

'''获取指定目录下的文件
   filepath:要遍历的目录
   filelist_out:输出文件列表
   file_ext:文件的扩展名,默认为任何类型的文件
'''
def getfilenames(filepath='',filelist_out=[],file_ext='all'):
    # 遍历filepath下的所有文件,包括子目录下的文件
    for fpath, dirs, fs in os.walk(filepath):
        for f in fs:
            fi_d = os.path.join(fpath, f)
            if file_ext == '.doc':  # 遍历Word文档文件
                if os.path.splitext(fi_d)[1] in ['.doc','.docx']:   # 判断是否为Word文件
                    filelist_out.append(re.sub(r'\\','/',fi_d))  # 添加到路径列表中
            else:
                if  file_ext == 'all':  # 要获取所有文件的情况
                    filelist_out.append(fi_d)  # 将文件路径添加到路径列表中
                elif os.path.splitext(fi_d)[1] == file_ext:  # 要获取除了Word文件以外的文件
                    filelist_out.append(fi_d)  # 将文件路径添加到路径列表中
                else:
                    pass
            filelist_out.sort()  # 对路径进行排序
    return filelist_out  # 返回文件完整路径列表


'''
功能:提取目录并保存到新的Word文档中
pdfpath:合并后的PDF文件绝对路径,包括文件名
listpath:目标路径
isPage:是否包含页码
level:目录层数
'''
def getPdfOutlines(pdfpath,listpath,isPage,level):
    with open(pdfpath, "rb") as file:
        doc = PdfFileReader(file)
        outlines = doc.getOutlines()  # 获取大纲
        global returnlist  # 全局变量,保存大纲的列表
        returnlist = []   # 创建一个空列表
        mylist = getOutline(outlines,isPage,level)  # 递归获取大纲
        w = DispatchEx("Word.Application")  # 创建Word文档应用程序对象
        w.Visible = 1
        w.DisplayAlerts = 0
        doc1 = w.Documents.Add()# 添加一个Word文档对象
        range1 = doc1.Range(0,0)
        for item in mylist:       # 通过循环将获取的目录列表插入到Word文档对象中
             range1.InsertAfter(item)
        outpath = os.path.join(listpath,'list.docx') # 连接Word文档路径

        doc1.SaveAs(outpath)  # 保存文件
        doc1.Close()  # 关闭Word文档对象
        w.Quit()  # 退出Word文档应用程序对象
    return outpath

'''
功能:提取指定层级的大纲
obj:Word文档的大纲对象
isPage:是否包含页码
selectLevel:目录层级,值为0~3的数。0表示全部大纲、1表示一级大纲……

'''
def getOutline(obj,isPage,selectLevel):  # 获取指定层级的大纲
    global returnlist
    for o in obj:
        if selectLevel == 1:  # 只提取一级标题
            if type(o).__name__ == 'Destination':
                dealPage(o, isPage)  # 输出大纲内容(处理是否包含页码)
        elif selectLevel == 2:  # 提取到二级标题
            if type(o).__name__ == 'Destination':
                dealPage(o, isPage)  # 输出大纲内容(处理是否包含页码)
            elif type(o).__name__ == 'list':
                getOne(o, isPage)
        elif selectLevel == 3:      # 提取到三级标题
            if type(o).__name__ == 'Destination':
                dealPage(o, isPage)  # 输出大纲内容(处理是否包含页码)
            elif type(o).__name__ == 'list':
                for o1 in o:
                    if type(o1).__name__ == 'Destination':
                        dealPage(o1, isPage)  # 输出大纲内容(处理是否包含页码)
                    elif type(o1).__name__ == 'list':
                        getOne(o1, isPage)
    return returnlist
def getOne(obj,isPage):  # 获取当前一级大纲
    for o in obj:
        if type(o).__name__ == 'Destination':
            dealPage(o, isPage)  # 输出大纲内容(处理是否包含页码)
    return returnlist
# 输出大纲内容(处理是否包含页码)
def dealPage(o,isPage):
    if isPage:  # 包括页码
        returnlist.append(o.get('/Title') + "\t\t" + str(o.get('/Page') + 1) + "\n")
    else:  # 不包括页码
        returnlist.append(o.get('/Title') + "\n")

# Word转换为PDF(多个文件)
def wordtopdf(filelist,targetpath):
    valueList = []
    try:
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        # 开始转换
        w = Dispatch("Word.Application")
        for fullfilename in filelist:
            (filepath,filename) = os.path.split(fullfilename)  # 分割文件路径和文件名,其中,filepath表示文件路径;filename表示文件名
            softfilename = os.path.splitext(filename)  # 分割文件名和扩展名
            os.chdir(filepath)  
            doc = os.path.abspath(filename)
            os.chdir(targetpath)
            pdfname = softfilename[0] + ".pdf"
            output = os.path.abspath(pdfname)
            pdf_name = output

            # 文档路径需要为绝对路径,因为Word启动后当前路径不是调用脚本时的当前路径。
            try: # 捕捉异常
                doc = w.Documents.Open(doc, ReadOnly=1)
                doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
                                        Item=constants.wdExportDocumentWithMarkup,
                                        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
            except Exception as e: # 处理异常
                print(e)
            if os.path.isfile(pdf_name): # 判断文件是否存在
                valueList.append(pdf_name) # 添加到文件列表中
            else:
                print('转换失败!')
                return False
        w.Quit(constants.wdDoNotSaveChanges) # 退出Word应用程序
        return valueList  # 返回生成PDF文件列表
    except TypeError as e:
        print('出错了!')
        print(e)
        return False
if __name__ == '__main__':
    sourcepath = r"E:/learn/test/doc/temp"  # 指定源路径(Word文档所在路径)
    targetpath = r"E:/learn/test/doc/pdf/"  # 指定目标路径(PDF保存路径)
    filelist = getfilenames(sourcepath,[],'.doc')  # 获取Word文档路径
    valueList = wordtopdf(filelist,targetpath)  # 实现将Word文档批量转换为PDF
    if valueList:
        # 将多个PDF文件合并为一个PDF文件
        mergefiles(targetpath, 'merged.pdf', True)
        temp = [os.path.join(targetpath , 'merged.pdf')] # 组合PDF文件路径
        for file in valueList:            # 遍历临时生成的PDF文件列表
            os.remove(file)                # 删除PDF文件
        resultvalue = getPdfOutlines(temp[0], targetpath, True,2)  # 提取目录
        os.remove(temp[0])  # 删除合并后的PDF文件
        print("提取完成!文件保存在:",targetpath )
    else:
        print("没有要提取目录的Word文档或者提取失败!")
	



004 商品竞猜价格游戏.

005根据计算机硬盘、主板、CPU生成注册信息…
006 语音版东北方言小词典…
007 DIY高考倒计时小软件.….
008自动计算消耗能量的虚拟跑步机
009数字大小写转换程序
010 RGB模式颜色转换器.
011 根据身份证号判断所属省份、生日及性别.
012超市购物小票随机抽奖程序
013 模拟生成福彩双色球彩票号码,
014挑战10秒小程序.
015验证输入的IP地址是否正确.
016摄氏温度和其他温度换算.
017混合加减法出题程序

猜你喜欢

转载自blog.csdn.net/qq_64505944/article/details/131302463