file = '新建文本文档.txt' with open(file,encoding='utf-8') as f: lines = f.readlines() print('lines为:',lines) split_list = [] for s in lines: s = s.strip() # 删除字符串两端的空格和换行符 #print('s为',s) split_list.append(s.split(':', 1)) # 用第一个冒号分割字符串,最多分割一次 first_list = [s[0] for s in split_list] second_list = [s[1] for s in split_list] new_second_list=[] print(first_list) print(second_list) for i in second_list: i = i.strip() # 删除字符串两端的空格和换行符 new_second_list.append(i) print(new_second_list) #转化为列表 dict = dict(zip(first_list,new_second_list)) print(dict) a = [] # SrcDatabase-来源库 b = [] # Title-题名 c = [] # Author-作者 d = [] # Organ-单位 e = [] # Source-文献来源 f = [] # PubTime-发表时间 g = [] # Volume-卷 h = [] # Period-期 for key,value in dict.items(): if 'SrcDatabase-来源库' in dict[key]: a.append(dict[value]) elif 'Title-题名' in dict[key]: b.append(dict[value]) elif 'Author-作者' in dict[key]: c.append(dict[value]) elif 'Organ-单位' in dict[key]: d.append(dict[value]) elif 'Source-文献来源' in dict[key]: e.append(dict[value]) elif 'PubTime-发表时间' in dict[key]: f.append(dict[value]) elif 'Volume-卷' in dict[key]: g.append(dict[value]) else: h.append(dict[value]) print('SrcDatabase-来源库:',a) print('Title-题名:',b) print('Author-作者:',c) print('Organ-单位:',d) print('Source-文献来源:',e) print('PubTime-发表时间',f) print('Volume-卷:',g) print('Period-期:',h) df = pd.DataFrame({"SrcDatabase-来源库":a,"Title-题名": b,"Author-作者":c,"Organ-单位": d,"Source-文献来源":e,"PubTime-发表时间": f,"Volume-卷":g,"Period-期": h}) df.to_excel("处理后的文档.xlsx", index=False)有问题吗,这个代码,如有,怎么解决

时间: 2023-06-06 11:05:40 浏览: 66
这段代码的作用是打开一个名为'新建文本文档.txt'的文件,并以utf-8的编码方式读取文件中的所有行,存储在一个列表变量lines中。接着对lines中每一个字符串进行去除空白符的操作(strip()函数),并把去除空白符后的字符串存储在一个新的列表变量split_list中。
相关问题

import os fasta_file = "E:\泛基因组分析\ORF\ORF_xml\PRRSV.fasta" new_id_file = "E:\泛基因组分析\ORF\ORF_xml\prr.txt" if not os.path.exists(fasta_file): print("Error: Fasta file does not exist!") exit() if not os.path.exists(new_id_file): print("Error: New id file does not exist!") exit() try: with open(new_id_file, "r",encoding="utf-8") as f: new_ids = [line.strip() for line in f] except: print("Error: Failed to read new id file!") exit() try: with open(fasta_file, "r",encoding="utf-8") as f: lines = f.readlines() except: print("Error: Failed to read fasta file!") exit() new_lines = [] for line in lines: if line.startswith(">"): # 获取当前id在新id列表中的索引 id_str = line.strip().lstrip(">") if id_str.isdigit(): index = int(id_str) - 1 else: try: index = new_ids.index(id_str) except ValueError: print("Error: Id not found in new id file! ({})".format(id_str)) exit() # 替换为新id new_lines.append(">{}\n".format(new_ids[index])) else: new_lines.append(line) # 将替换后的fasta文件写入新文件 with open("E:\泛基因组分析\ORF\ORF_xml\1.fasta", "w") as f: f.writelines(new_lines)

这个代码看起来已经很完整了,不过还是有一些可以改进的地方: 1. 在文件路径中使用“\\”或者“/”代替“\”,因为“\”是转义字符,容易出现错误。 2. 可以添加一些输入输出路径的提示信息,方便用户操作。 3. 可以添加一个函数来判断文件是否存在,避免代码重复。 4. 可以将代码分解成多个函数,提高代码的可读性和可维护性。 下面是一个改进版本的代码,你可以参考一下: ```python import os def check_file(file_path): if not os.path.exists(file_path): print("Error: File does not exist! ({})".format(file_path)) return False return True def read_file(file_path): try: with open(file_path, "r", encoding="utf-8") as f: lines = f.readlines() return lines except: print("Error: Failed to read file! ({})".format(file_path)) return None def replace_seq_id(fasta_file, new_id_file, output_file): if not check_file(fasta_file): exit() if not check_file(new_id_file): exit() new_ids = read_file(new_id_file) if new_ids is None: exit() lines = read_file(fasta_file) if lines is None: exit() new_lines = [] for line in lines: if line.startswith(">"): # 获取当前id在新id列表中的索引 id_str = line.strip().lstrip(">") if id_str.isdigit(): index = int(id_str) - 1 else: try: index = new_ids.index(id_str) except ValueError: print("Error: Id not found in new id file! ({})".format(id_str)) exit() # 替换为新id new_lines.append(">{}\n".format(new_ids[index].strip())) else: new_lines.append(line) # 将替换后的fasta文件写入新文件 with open(output_file, "w") as f: f.writelines(new_lines) if __name__ == "__main__": fasta_file = input("Please input fasta file path: ") new_id_file = input("Please input new id file path: ") output_file = input("Please input output file path: ") replace_seq_id(fasta_file, new_id_file, output_file) ``` 这个版本的代码中,添加了三个函数分别用来检查文件是否存在、读取文件内容和替换序列ID。在主函数中,通过输入文件路径来执行替换操作。

import os import datetime import time # 原文件夹路径和目标文件夹路径 src_path = r"Z:\看板v2" dst_path = r"D:\測試log" while True: # 获取今天日期,并格式化成指定的形式 today = datetime.date.today() formatted_today = today.strftime("%Y%m%d") # 构造目标文件的完整路径 dst_file = os.path.join(dst_path, f"當天測試log.txt") # 记录程序开始运行时间 start_time = time.time() # 遍历原文件夹,查找当天日期的 TXT 文件 txt_files = [] for root, dirs, files in os.walk(src_path): for file in files: if file.endswith(".txt") and file.startswith(formatted_today): txt_files.append(os.path.join(root, file)) # 如果找到符合条件的 TXT 文件,则将它们合并到目标文件中 if len(txt_files) > 0: with open(dst_file, "w", encoding="utf-8") as f: for src_file in txt_files: # 读取 TXT 文件的内容,并写入目标文件中 with open(src_file, "r", encoding="utf-8") as txt_file: content = txt_file.read() f.write(content) print(f"{len(txt_files)} 个符合条件的 TXT 文件已成功合并到目标文件 當天測試log.txt 中!") else: print("未找到符合条件的 TXT 文件!") # 计算程序运行时间 end_time = time.time() run_time = end_time - start_time now = datetime.datetime.now() # 输出程序运行时间 print(f"程序运行时间:{run_time:.2f} 秒 {now.strftime('%Y-%m-%d %H:%M:%S')}") # 暂停15秒钟 time.sleep(15)

好的,以下是修改后的代码,已实现删除第一列和第三列重复数据的功能: ``` python import os import datetime import time # 原文件夹路径和目标文件夹路径 src_path = r"Z:\看板v2" dst_path = r"D:\測試log" while True: # 获取今天日期,并格式化成指定的形式 today = datetime.date.today() formatted_today = today.strftime("%Y%m%d") # 构造目标文件的完整路径 dst_file = os.path.join(dst_path, f"當天測試log.txt") # 记录程序开始运行时间 start_time = time.time() # 遍历原文件夹,查找当天日期的 TXT 文件 txt_files = [] for root, dirs, files in os.walk(src_path): for file in files: if file.endswith(".txt") and file.startswith(formatted_today): txt_files.append(os.path.join(root, file)) # 如果找到符合条件的 TXT 文件,则将它们合并到目标文件中 if len(txt_files) > 0: with open(dst_file, "w", encoding="utf-8") as f: for src_file in txt_files: # 读取 TXT 文件的内容,并处理后写入目标文件中 with open(src_file, "r", encoding="utf-8") as txt_file: # 读取所有行,并转换为列表形式 lines = txt_file.readlines() # 删除第一列 del lines[0] # 获取第三列数据 col3_data = [] for line in lines: data = line.split("\t")[2] col3_data.append(data) # 删除第三列重复数据 col3_data = list(set(col3_data)) # 将剩下的行写入目标文件中 f.write(lines[0]) for i in range(1, len(lines)): if lines[i].split("\t")[2] in col3_data: f.write(lines[i]) print(f"{len(txt_files)} 个符合条件的 TXT 文件已成功合并到目标文件 當天測試log.txt 中!") else: print("未找到符合条件的 TXT 文件!") # 计算程序运行时间 end_time = time.time() run_time = end_time - start_time now = datetime.datetime.now() # 输出程序运行时间 print(f"程序运行时间:{run_time:.2f} 秒 {now.strftime('%Y-%m-%d %H:%M:%S')}") # 暂停15秒钟 time.sleep(15) ``` 修改后,程序会读取所有行并转换为列表形式,然后删除第一列,获取第三列数据,并将第三列数据存储到列表中。接着,程序会删除第三列重复数据并将剩下的行写入目标文件中。

相关推荐

将下列代码改为对上海证券交易所网站公告爬取from concurrent.futures import ThreadPoolExecutor import requests headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.159 Safari/537.36" } def download_pdf(url, code, num, date): print(f'开始下载 data/{code}_{date}_{num}.pdf') resp = requests.get(url, headers=headers) with open(f'E:/深交所pdf/{code}_{date}_{num}.pdf', 'wb') as f: f.write(resp.content) resp.close() print(f'E:/深交所pdf/{code}_{date}_{num}.pdf 下载完毕!') if __name__ == '__main__': domain = 'http://www.sse.cn' with ThreadPoolExecutor(30) as t: with open('target.csv', 'r') as f: lines = f.readlines() for line in lines: param = list(line.split()) form = { 'seDate': [param[3], param[3]], 'stock': [param[0]], 'channelCode': ['listedNotice_disc'], 'pageSize': '50', 'pageNum': '1' } # 获取文件列表的url get_file_list_url = 'http://www.sse.com.cn/disclosure/listedinfo/announcement/json/announce_type.json?v=0.9715488799747511' resp = requests.post(get_file_list_url, headers=headers, json=form) # resp.encoding = 'utf-8' # print(resp.json()) js = resp.json() resp.close() tot = 0 for data in js['data']: tot += 1 download_url = domain + f'/api/disc/info/download?id={data["id"]}' t.submit(download_pdf, url=download_url, code=param[0], num=tot, date=param[3]) print("下载完毕!!!") # doc_id = '' # download_url = domain + f'/api/disc/info/download?id={"c998875f-9097-403e-a682-cd0147ce10ae"}' # resp = requests.get(download_url, headers=headers) # with open(f'{"c998875f-9097-403e-a682-cd0147ce10ae"}.pdf', 'wb') as f: # f.write(resp.content) # resp.close()

import tensorflow as tf import numpy as np import tkinter as tk from tkinter import filedialog import time import pandas as pd import stock_predict as pred def creat_windows(): win = tk.Tk() # 创建窗口 sw = win.winfo_screenwidth() sh = win.winfo_screenheight() ww, wh = 800, 450 x, y = (sw - ww) / 2, (sh - wh) / 2 win.geometry("%dx%d+%d+%d" % (ww, wh, x, y - 40)) # 居中放置窗口 win.title('LSTM股票预测') # 窗口命名 f_open =open('dataset_2.csv') canvas = tk.Label(win) canvas.pack() var = tk.StringVar() # 创建变量文字 var.set('选择数据集') tk.Label(win, textvariable=var, bg='#C1FFC1', font=('宋体', 21), width=20, height=2).pack() tk.Button(win, text='选择数据集', width=20, height=2, bg='#FF8C00', command=lambda: getdata(var, canvas), font=('圆体', 10)).pack() canvas = tk.Label(win) L1 = tk.Label(win, text="选择你需要的 列(请用空格隔开,从0开始)") L1.pack() E1 = tk.Entry(win, bd=5) E1.pack() button1 = tk.Button(win, text="提交", command=lambda: getLable(E1)) button1.pack() canvas.pack() win.mainloop() def getLable(E1): string = E1.get() print(string) gettraindata(string) def getdata(var, canvas): global file_path file_path = filedialog.askopenfilename() var.set("注,最后一个为label") # 读取文件第一行标签 with open(file_path, 'r', encoding='gb2312') as f: # with open(file_path, 'r', encoding='utf-8') as f: lines = f.readlines() # 读取所有行 data2 = lines[0] print() canvas.configure(text=data2) canvas.text = data2 def gettraindata(string): f_open = open(file_path) df = pd.read_csv(f_open) # 读入股票数据 list = string.split() print(list) x = len(list) index=[] # data = df.iloc[:, [1,2,3]].values # 取第3-10列 (2:10从2开始到9) for i in range(x): q = int(list[i]) index.append(q) global data data = df.iloc[:, index].values print(data) main(data) def main(data): pred.LSTMtest(data) var.set("预测的结果是:" + answer) if __name__ == "__main__": creat_windows()这个代码能实现什么功能

最新推荐

recommend-type

2107381120 王孟丽 实验2 (1).docx

2107381120 王孟丽 实验2 (1).docx
recommend-type

Java项目如何打成可以运行Jar包

Java项目如何打成可以运行Jar包
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

可见光定位LED及其供电硬件具体型号,广角镜头和探测器,实验设计具体流程步骤,

1. 可见光定位LED型号:一般可使用5mm或3mm的普通白色LED,也可以选择专门用于定位的LED,例如OSRAM公司的SFH 4715AS或Vishay公司的VLMU3500-385-120。 2. 供电硬件型号:可以使用常见的直流电源供电,也可以选择专门的LED驱动器,例如Meanwell公司的ELG-75-C或ELG-150-C系列。 3. 广角镜头和探测器型号:一般可采用广角透镜和CMOS摄像头或光电二极管探测器,例如Omron公司的B5W-LA或Murata公司的IRS-B210ST01。 4. 实验设计流程步骤: 1)确定实验目的和研究对象,例如车辆或机器人的定位和导航。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

解释这行代码 c = ((double)rand() / RAND_MAX) * (a + b - fabs(a - b)) + fabs(a - b);

这行代码的作用是随机生成一个浮点数,范围在 a 和 b 之间(包括 a 和 b)。 其中,`rand()` 函数是 C 语言标准库中的一个函数,用于生成一个伪随机整数。`RAND_MAX` 是一个常量,它表示 `rand()` 函数生成的随机数的最大值。 因此,`(double)rand() / RAND_MAX` 表示生成的随机数在 [0, 1] 之间的浮点数。 然后,将这个随机数乘上 `(a - b) - fabs(a - b)`,再加上 `fabs(a - b)`。 `fabs(a - b)` 是 C 语言标准库中的一个函数,用于计算一个数的绝对值。因此,`fabs(a - b)