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()
相关推荐
断竿散人13 小时前
乾坤微前端框架的沙箱技术实现原理深度解析
前端·javascript·前端框架
进阶的鱼13 小时前
(4种场景)单行、多行文本超出省略号隐藏
前端·css·面试
月亮慢慢圆13 小时前
拖拽API
前端
知了一笑13 小时前
独立做产品,做一个,还是做多个找爆款?
前端·后端·产品
uhakadotcom13 小时前
在python中,使用conda,使用poetry,使用uv,使用pip,四种从效果和好处的角度看,有哪些区别?
前端·javascript·面试
_AaronWong13 小时前
Electron 桌面应用侧边悬浮窗口设计与实现
前端·electron
玲小珑13 小时前
LangChain.js 完全开发手册(九)LangGraph 状态图与工作流编排
前端·langchain·ai编程
鹏多多13 小时前
深入解析vue的keep-alive缓存机制
前端·javascript·vue.js
JarvanMo13 小时前
用 `alice` 来检查 Flutter 中的 HTTP 调用
前端
小图图13 小时前
Claude Code 黑箱揭秘
前端·后端