code:
import difflib
import json
import os
# 示範用的資料
log_sensors = ["temperture", "humidy", "presure"] # 可能打錯的文字
rd_sensors = ["temperature", "humidity", "pressure", "voltage", "current"] # 正確的文字
# 建立空字典來存储匹配結果
matches = {}
# 對每個 log_sensors 中的項目尋找相似項
for sensor in log_sensors:
# 使用 difflib 尋找相似的文字
# n=5: 最多回傳5個匹配結果
# cutoff=0.6: 相似度閾值,0~1之間,越大要求越嚴格
match = difflib.get_close_matches(sensor, rd_sensors, n=5, cutoff=0.6)
# 如果找到匹配項,存入字典;沒找到則存入 None
if match:
matches[sensor] = match
else:
matches[sensor] = None
# 印出比對結果
print(f"原始文字: {sensor}")
print(f"相似項目: {match}")
print("-" * 30)
# 設定輸出路徑
# 假設目前在 /path/to/project
dirname = "/path/to/project"
dir_ex = os.path.join(dirname, "export")
path_ex = os.path.join(dir_ex, "similar.json")
# 建立輸出資料夾(如果不存在)
os.makedirs(dir_ex, exist_ok=True)
# 將結果寫入 JSON 檔案
with open(path_ex, "w", encoding="UTF-8") as f:
json.dump(matches, f, indent=4, ensure_ascii=False)
print(f"檔案已經輸出到\n{path_ex}")輸出結果:

json:

這個程式的主要功能:
- 比對兩個列表中的相似文字
- 使用 difflib 進行模糊匹配
- 將結果整理成字典格式
- 輸出成易讀的 JSON 檔案
常用參數說明:
n: 要返回的最大匹配數量cutoff: 相似度閾值(0.6 表示需要 60% 相似)indent: JSON 檔案的縮排格式ensure_ascii: 設為 False 可正確處理中文
推薦hahow線上學習python: https://igrape.net/30afN
![Python網路爬蟲requests 如何下載台灣證交所的opendata? rawData = requests. get (inputs) #<Response [200]> Python網路爬蟲requests 如何下載台灣證交所的opendata? rawData = requests. get (inputs) #<Response [200]>](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2022/10/20221004135740_43.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/10/20251021155823_0_c16012.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




![Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()] Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()]](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/11/20241123194900_0_5218de.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言