1. 将一个文件中的所有英文字母转换成大写,复制到另一文件中。

fi=open("ex01.py",'r')
fo=open("f2.txt",'w')
for line in fi:
    line=line.upper()
    fo.write(line)
fi.close()
fo.close()

2. 将一个文件中的指定单词删除后,复制到另一个文件中。

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()

3. 从键盘输入一个整数,求100除以它的商,并显示。要求对从键盘输入的数值进行异常处理。

n=eval(input("请输入数值:"))
try:
    s=100/n
    print(s)
except Exception as ee:
    print(ee)

4. 爬虫案例:爬取2024高校排名信息。

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()

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部