这两个实验怎么输都不对,不太会编这两个实验,寻求大家的帮助
1条回答 默认 最新
- 加勒比海鸡_ 2022-11-04 04:11关注
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")
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥20 RL+GNN解决人员排班问题时梯度消失
- ¥15 统计大规模图中的完全子图问题
- ¥15 使用LM2596制作降压电路,一个能运行,一个不能
- ¥60 要数控稳压电源测试数据
- ¥15 能帮我写下这个编程吗
- ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
- ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
- ¥20 @microsoft/fetch-event-source 流式响应问题
- ¥15 ogg dd trandata 报错
- ¥15 高缺失率数据如何选择填充方式