1. 程式人生 > 實用技巧 >Python 修改剪下板方法(二) pyperclip 庫

Python 修改剪下板方法(二) pyperclip 庫

import pyperclip
import re
import time

class jianting():

    def __init__(self):
        # 初始化替換字元列表,相比於正則使用replace函式進行單字元替換更快
        self.char_list = [('', '('),
                     ('', ')'),
                     ('', '"'),
                     ('', '"'),
                     ('', '\''),
                     (
'', '\''), ('print ', 'print '), ('版權宣告:本文為CSDN', '版權宣告:本文為CSDN'), (' ', ''), ('\n', ''), (';', ''), (':', ''), ('?', ''), ]
# 預編譯正則替換匹配表示式 # 匹配python2格式的 print函式文字 self.sub_print = re.compile(r'\bprint\s+(.+)') # 匹配csdn複製自帶的版權聲明後綴文字 self.sub_csdn = re.compile(r'—+\s+版權宣告:本文為CSDN.*\s+原文連結.*') def clipboard_get(self): """獲取剪貼簿資料""" data = pyperclip.paste() return
data def clipboard_set(self,data): """設定剪貼簿資料""" pyperclip.copy(data) # 指定場景 sub替換函式:python2格式的 print函式 替換為python3格式 def sub_fn(self,s): return 'print(' + s.group(1).strip() + ')\r\n' # 判斷如果沒有要替換的字元則返回None,有則執行替換操作,先進行字元列表replace,再執行reg.sub(sub_fn, txt) def char_replace_reg_sub(self,txt): new_txt = txt # 對字元列表中字元 逐一判斷,如果字元在文字中 則replace替換,如果都不在 則return None,不用再進行替換操作 i = 0 for old_char, new_char in self.char_list: if old_char in new_txt: i += 1 new_txt = new_txt.replace(old_char, new_char) if i == 0: return None print('-' * 150, '\n【After char replace】:', new_txt) # 對指定場景替換 使用正則re.sub new_txt = self.sub_print.sub(self.sub_fn, new_txt) new_txt = self.sub_csdn.sub('', new_txt) print('【After sub replace:】', new_txt) #lihai().hah(new_txt) return new_txt def main(self): """後臺指令碼:每隔0.2秒,讀取剪下板文字,檢查有無指定字元或字串,如果有則執行替換""" # recent_txt 存放最近一次剪下板文字,初始化值只多執行一次paste函式讀取和替換 recent_txt = self.clipboard_get() replaced_txt = self.char_replace_reg_sub(recent_txt) self.clipboard_set(recent_txt if replaced_txt is None else replaced_txt) while True: # txt 存放當前剪下板文字 txt = self.clipboard_get() # 剪下板內容和上一次對比如有變動,再進行內容判斷,判斷後如果發現有指定字元在其中的話,再執行替換 if txt != recent_txt: # print(f'txt:{txt}') new_txt = self.char_replace_reg_sub(txt) # 沒查到要替換的子串,返回None if new_txt is not None: self.clipboard_set(new_txt) # 更新 recent_txt 為替換之後的文字,便於下次與 txt 剪下板文字對比,判斷內容有無更新 recent_txt = new_txt return recent_txt else: return txt # 檢測間隔(延遲0.2秒) time.sleep(0.2) class niubi(): def lihai(self): while True: #jianting().main() #t= lihai() t = jianting().main() print(t) if __name__ == '__main__': niubi().lihai()