请教一下这两个实验,非常感谢

img

img

这两个实验怎么输都不对,不太会编这两个实验,寻求大家的帮助


        lst = []
        with open("data.txt","r",encoding="utf-8") as f:
            linenum = len(f.readlines()) #获取行数
            f.seek(0) # 光标定位到文档开头
            for i in range(linenum):
                line = f.readline().strip("\n").replace(" ","").rstrip(",")# 去除回车,空格
                if line != '': # 判断是否读取到空行
                    list = line.split(",")# 列表生成式 通过','拆分成列表
                    lst.extend(list) # 添加到lst列表
        lst = [int(i) for i in lst]# 列表生成式 将列表内容转为int类型
        lst.sort() # 排序
        lst = [str(i) for i in lst]  # 列表生成式 将列表内容转为str类型
        with open("data_asc.txt","w",encoding="utf-8") as f: # 写入文件
          f.write(",".join(lst))
    with open("hamlet.txt", "r", encoding="utf-8") as f:
        txt = f.read().replace("\n", " ")
        txt = txt.replace("!", " ").replace("\"", " ").replace("#", " ")
        txt = txt.replace("$", " ").replace("%", " ").replace("&", " ")
        txt = txt.replace("(", " ").replace(")", " ").replace("*", " ")
        txt = txt.replace("+", " ").replace(",", " ").replace("-", " ")
        txt = txt.replace(".", " ").replace("/", " ").replace(":", " ")
        txt = txt.replace(";", " ").replace("<", " ").replace("=", " ")
        txt = txt.replace(">", " ").replace("?", " ").replace("@", " ")
        txt = txt.replace("[", " ").replace("\\", " ").replace("]", " ")
        txt = txt.replace("^", " ").replace("_", " ").replace("'", " ")
        txt = txt.replace("{", " ").replace("|", " ").replace("}", " ")
        txt.replace("~", " ").replace("‘", " ")
        txt = txt.lower()
        list = txt.split(" ")
        # print(list)
        dictdict_data = {}
        for i in list:
            if i =='': # 判断是否有空行
                continue
            if not i in dictdict_data: 
                dictdict_data[i] = 1 # 第一次添加到字典
            else:
                dictdict_data[i] = dictdict_data[i] + 1 # 追加添加到字典

        a = sorted(dictdict_data.items(), key=lambda x: x[1],reverse=True) # 字典排序 具体可百度字典排序的方法
        dict_data=dict(a)
        for d in range(len(dict_data)):
            if len(dict_data)>10:
                dict_data.popitem()
        with open("hamlet_data.txt",'w',encoding='utf-8') as f2:
            for j in dict_data:
                s=(j+" "+str(dict_data[j]))
                f2.write(s)
                f2.write("\n")