在貼吧、論壇等地方出於各種原因發度盤鏈接容易被吞,於是有很多常見的防和諧套路:比如說“鏈接中加’刪除中文‘”、“.“替換爲’點‘”、”不加前綴“等……
我查了下這功能也沒人寫,估計都是手動處理忍忍就完了。索性我寫一個。
以後要是會開發瀏覽器插件或看看有沒有插件可以集成,我就整個瀏覽器插件(立flag不負責~)
1.去除中文和空格:
import re
#去除中文
def do_unchinese(file):
pattern = re.compile(r'[\u4e00-\u9fa5]')
#pattern = re.compile(r'[^\u4e00-\u9fa5]')#這句是去除非中文
unchinese = re.sub(pattern,"",file)
return unchinese
#去除空格
def do_unblank(file):
return file.replace(" ", "")
if __name__ == "__main__":
line = "ht tps ://blog.cs dn.net/ sinat _273 82047"
print("原文:")
print(line)
print("保留非中文:")
print(do_unchinese(line))
print("保留非中文+刪除空格:")
print(do_unblank(do_unchinese(line)))
效果先不截圖了,下面綜合的截圖包括這個功能了
2.去除中文和空格外,再加上”點“替換、檢測並加前綴的功能:
import re
#去除中文
def do_unchinese(file):
pattern = re.compile(r'[\u4e00-\u9fa5]')
#pattern = re.compile(r'[^\u4e00-\u9fa5]')#去除非中文
unchinese = re.sub(pattern,"",file)
return unchinese
#去除空格
def do_unblank(file):
return file.replace(" ", "")
#替換中文“點”爲"."
def do_dot(file):
return file.replace("點", ".")
#處理前綴
def do_prefix(file):
#有前綴
if "pan.baidu.com/s/" in file:
return file
#有部分前綴,或者不乾淨的前綴(正則表達式處理)
if "/s/" in file:
return re.sub(".*/s/", "pan.baidu.com/s/", file)#“.*”用於匹配任意字符
#沒有前綴
else:
return "pan.baidu.com/s/" + file
if __name__ == "__main__":
line = "點com/s防/1BS FGM和byQk 諧1F q刪g除 o4z中L5 文WX4A"
line=do_unchinese(line)
line=do_unblank(line)
line=do_dot(line)
line=do_prefix(line)#前綴,一定要在最後處理,防止空格和中文的干擾
print("處理結果:")
print(line)
效果(這是比較喪心病狂地加東西了):
參考:
Python中常見字符串去除空格的方法總結
python 去除非中文字符
Python判斷一個字符串是否包含子串的幾種方法
python 字符串替換功能 string.replace()可以用正則表達式,更優雅
https://www.runoob.com/python/python-reg-expressions.html
另外,看一篇百度經驗說webbb.fun加前綴很好用,我還沒試過。