python编程题3

  1. 将一个文件中的所有英文字母转换成大写,复制到另一文件中。
python 复制代码
fi=open("ex01.py",'r')
fo=open("f2.txt",'w')
for line in fi:
    line=line.upper()
    fo.write(line)
fi.close()
fo.close()
  1. 将一个文件中的指定单词删除后,复制到另一个文件中。
python 复制代码
fi=open("ex02.py",'r')
fo=open("f2.txt",'w')
deleteword="line"
for line in fi:
    line1=line.replace(deleteword,"")
    #print(line1)
    fo.write(line1)
fi.close()
fo.close()
  1. 从键盘输入一个整数,求100除以它的商,并显示。要求对从键盘输入的数值进行异常处理。
python 复制代码
n=eval(input("请输入数值:"))
try:
    s=100/n
    print(s)
except Exception as ee:
    print(ee)
  1. 爬虫案例:爬取2024高校排名信息。
python 复制代码
from urllib.request import urlopen
import bs4
import matplotlib.pyplot as plt
import csv
def getHtml(url):
    try:
        response = urlopen(url)
        # print(response)
        return response.read().decode('utf-8')
    except:
        return ""

def getUnivInfo(csvfile, html):
    soup = bs4.BeautifulSoup(html, "html.parser")
    csv_writer = csv.writer(csvfile)
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):

            tds = tr('td')
            l1=tds[1].find('a').string
            # print(tds[2].prettify().splitlines())
            l2=tds[2].prettify().splitlines()[1][1:]
            #
            # print(l2)
            l3=tds[5].string
            csv_writer.writerow([tds[0].div.string.rstrip().lstrip(),l1,l2,l3])


def printTopUniv(csvfile, num):
    fmt = "{0:^4}\t{1:{3}<10}\t{2:^5}"
    print(fmt.format("排名", "学校", "总分", chr(12288)))
    csvfile.seek(0, 0)
    recs = csv.reader(csvfile)
    for rec in recs:
        print(fmt.format(rec[0], rec[1], rec[3], chr(12288)))
        if int(rec[0]) == num:
            break


def showUnivDictr(csvfile, num):
    udict = {}
    csvfile.seek(0, 0)
    recs = csv.reader(csvfile)

    for rec in recs:
        print(rec)
        udict[rec[2]] = udict.get(rec[2], 0) + 1
        if int(rec[0]) == num:
            break

    sort_udict = dict(sorted(udict.items(), key=lambda item: item[1], reverse=True))
    plt.rcParams['font.family'] = 'Simhei'
    results = [0 for i in range(6)]
    plt.title('中国前100名大学分布')
    plt.xlabel('省/直辖市')
    plt.ylabel('大学数量')
    plt.xticks(range(1, len(sort_udict) + 1), sort_udict.keys())
    plt.bar(range(1, len(sort_udict) + 1), sort_udict.values(), width=0.6)
    plt.savefig('univ_visua12.png')
    plt.show()


def main():
    csvfile = open('univ_rank.csv', 'w+', newline='')
    url='https://www.shanghairanking.cn/rankings/bcur/202411'
    html = getHtml(url)

    getUnivInfo(csvfile, html)
    printTopUniv(csvfile, 30)
    showUnivDictr(csvfile, 100)
    csvfile.close()


main()
相关推荐
是有头发的程序猿1 分钟前
Python爬虫防AI检测实战指南:从基础到高级的规避策略
人工智能·爬虫·python
grd41 分钟前
Electron for OpenHarmony 实战:Pagination 分页组件实现
python·学习
CryptoRzz3 分钟前
印度交易所 BSE 与 NSE 实时数据 API 接入指南
java·c语言·python·区块链·php·maven·symfony
光影少年5 分钟前
前端如何虚拟列表优化?
前端·react native·react.js
Moment6 分钟前
一杯茶时间带你基于 Yjs 和 reactflow 构建协同流程图编辑器 😍😍😍
前端·后端·面试
躲在云朵里`7 分钟前
Linux环境下部署SpringBoot前后端分离项目
linux·服务器
山土成旧客10 分钟前
【Python学习打卡-Day35】从黑盒到“玻璃盒”:掌握PyTorch模型可视化、进度条与推理
pytorch·python·学习
@zulnger11 分钟前
python 学习笔记(循环)
笔记·python·学习
No_Merman17 分钟前
【DAY28】元组和os模块
python
橘颂TA19 分钟前
【Linux】从 “抢资源” 到 “优雅控场”:Linux 互斥锁的原理与 C++ RAII 封装实战(Ⅰ)
linux·运维·服务器·c++·算法