从百度文库复制的文本格式混乱。如下图所示:每次复制的文本,都需要花些时间逐行整理,很是费时。为了自动化的解决这一问题,我写了一段python代码。代码如下:
''' 从百度文库复制的文本格式混乱,本工具用来对混乱的文本进行整理 ''' import os import re import tkinter as tk from tkinter import filedialog root = tk.Tk() root.title = "百度文库复制文本格式化工具" filename = tk.StringVar() info = tk.StringVar() txt_filetype = [('文本文件', '.txt')] def selectFile(): filepath = filedialog.askopenfilename(parent=root, initialdir=os.getcwd(), title="请选择文本文件", filetypes=txt_filetype) filename.set(filepath) # 设置变量filename的值 def fileSave(): txtfilepath = filename.get() if txtfilepath == '': info.set("未选择文件") return if not os.path.exists(txtfilepath): info.set("文件不存在") return if not txtfilepath.endswith(".txt"): info.set("文件不是文本文件") return with open(txtfilepath, 'r', encoding='utf-8') as f: ms = f.readlines() data = '' me = '' re_end = re.compile('[。:?!…]$') for s in ms: s2 = s.strip() me += s.rstrip() if re_end.search(s2): data += me + '\n' me = '' if me != '': data += me outpath = txtfilepath[:-4] + '_ft' + '.txt' with open(outpath, 'w', encoding='utf-8') as f: f.write(data) info.set(outpath) # 设置变量filenewname的值 # 构建“选择文件”这一行的标签、输入框以及启动按钮,同时我们希望当用户选择图片之后能够显示原图的基本信息 tk.Label(root, text='选择文件').grid(row=1, column=0, padx=5, pady=5) tk.Entry(root, textvariable=filename).grid(row=1, column=1, padx=5, pady=5) tk.Button(root, text='打开文件', command=selectFile).grid(row=1, column=2, padx=5, pady=5) # 构建“保存文件”这一行的标签、输入框以及启动按钮 tk.Label(root, text='保存文件').grid(row=2, column=0, padx=5, pady=5) tk.Button(root, text='保存', command=fileSave).grid(row=2, column=1, padx=5, pady=5, sticky="w") # 构建“选择目录”这一行的标签、输入框以及启动按钮 tk.Label(root, text='信息').grid(row=3, column=0, padx=5, pady=5) tk.Label(root, textvariable=info).grid(row=3, column=1, padx=5, pady=5, columnspan=2, sticky="w") root.mainloop()
下面是运行时的窗口使用方法也很简单,先点击打开文件,然后点保存就可以了。 混乱的百度文库复制文本经过整理过后的格式如下图:
如上所示,文本已经被分段整理好了。 上面的代码的原理很简单,概述如下: 对混乱的百度文库复制文本逐行判断,如果在这一行的后面发现了。:?!…句子结束标点,则进行换行,否则不换行。 要想运行上面的python代码,需要安装python,下载地址: