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 13:05:40 浏览: 110
新建文本文档.txt
这段代码的作用是打开一个名为'新建文本文档.txt'的文件,并以utf-8的编码方式读取文件中的所有行,存储在一个列表变量lines中。接着对lines中每一个字符串进行去除空白符的操作(strip()函数),并把去除空白符后的字符串存储在一个新的列表变量split_list中。
阅读全文