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()
相关推荐
IT·陈寒10 分钟前
Kotlin vs Java:深入解析两者之间的最新差异与优劣(全面指南)
java·python·kotlin
go2coding16 分钟前
开源 复刻GPT-4o - Moshi;自动定位和解决软件开发中的问题;ComfyUI中使用MimicMotion;自动生成React前端代码
前端·react.js·前端框架
月清晖17 分钟前
centos更换yum源、安装Docker和换源
linux·docker·centos
知识分享小能手31 分钟前
从新手到高手:Scala函数式编程完全指南,Scala 访问修饰符(6)
大数据·开发语言·后端·python·数据分析·scala·函数式编程
freesharer36 分钟前
Zabbix 配置WEB监控
前端·数据库·zabbix
web前端神器36 分钟前
forever启动后端服务,自带日志如何查看与设置
前端·javascript·vue.js
elderingezez39 分钟前
2024年用scrapy爬取BOSS直聘的操作
爬虫·python·scrapy
【 教主 】39 分钟前
<Linux> 多线程
linux·运维·服务器
是Yu欸42 分钟前
【前端实现】在父组件中调用公共子组件:注意事项&逻辑示例 + 将后端数组数据格式转换为前端对象数组形式 + 增加和删除行
前端·vue.js·笔记·ui·vue
Eiceblue1 小时前
用Python轻松转换Markdown文件为PDF文档
开发语言·vscode·python·pdf·word