Python文本处理:去除空行和空格
要在处理文本时去掉空行和空格,可以在 process_text 函数中添加相应的逻辑。以下是更新后的示例程序:
import tkinter as tk
import pyperclip
def paste_text():
text = pyperclip.paste()
text_entry1.delete(1.0, tk.END)
text_entry1.insert(tk.END, text)
def copy_text():
text = text_entry2.get(1.0, tk.END)
pyperclip.copy(text)
def process_text():
text = text_entry1.get(1.0, tk.END)
lines = text.split('
')
processed_lines = []
for line in lines:
line = line.strip() # 去除首尾空格
if line and '----' in line: # 去除空行并包含 '----' 的行
processed_lines.append(line.replace('----', ' '))
processed_text = '
'.join(processed_lines)
text_entry2.delete(1.0, tk.END)
text_entry2.insert(tk.END, processed_text)
window = tk.Tk()
text_label1 = tk.Label(window, text="文本框1:")
text_label1.pack()
text_entry1 = tk.Text(window, height=10, width=30)
text_entry1.pack()
paste_button = tk.Button(window, text="粘贴", command=paste_text)
paste_button.pack()
text_label2 = tk.Label(window, text="文本框2:")
text_label2.pack()
text_entry2 = tk.Text(window, height=10, width=30)
text_entry2.pack()
copy_button = tk.Button(window, text="复制", command=copy_text)
copy_button.pack()
process_button = tk.Button(window, text="处理", command=process_text)
process_button.pack()
window.mainloop()
在更新后的 process_text 函数中,我添加了 line.strip() 来去除每行的首尾空格。然后,使用条件语句 if line and '----' in line 来判断是否为空行并包含 '----'。只有满足条件的行才会被加入到处理后的文本中。
通过这个更新,处理后的文本将不再包含空行和首尾空格。你可以根据需要对界面进行调整和修改,以适应你的实际需求。
原文地址: https://www.cveoy.top/t/topic/Qco 著作权归作者所有。请勿转载和采集!