我有一個字典output_dict
,它包含與文件簽名及其相關擴展有關的數據,即'43 44 30 30 31': '.ISO'
。我正在嘗試編寫一個腳本,它將以字節爲單位讀取文件並返回字典中的任何匹配項。如果找不到匹配,則返回最相似的值。將輸入字符串與類似的字典鍵匹配Python
有沒有辦法讓它逐字節地讀取一個文件,匹配它,直到達到一個破壞匹配的字節,返回先前匹配的鍵/值?
另外,我希望它能夠匹配一個確定的數量,或匹配非常相似的東西(2-3個字節的差異)。如果沒有匹配或沒有類似的對象,我會希望它打印一條消息。
此刻,我的代碼看起來是這樣的:
root_path = "testdir"
list_of_files = os.listdir(root_path)
for files in list_of_files:
full_path = os.path.join(root_path, files)
open_it = open(full_path, 'rb')
read_it = open_it.read(x)
convert_it = get_bytes_as_displayable_hex(read_it)
convert_to_ascii = convert_it.encode('utf-8')
convert_to_string = convert_to_ascii.decode(encoding='utf-8', errors="strict")
result = (output_dict.get(convert_to_string))
if result is not None:
print("Scan complete, found: {} file(s)".format(result))
else:
result = difflib.get_close_matches(convert_to_string, output_dict, 2, 0.2)
print(result)
因此,預計結果會是這樣一個文件的前4個字節25 50 44 46這些字節的交叉與德字典引用,並且會匹配它,結果返回「.PDF」。
如果前四個字節是25 50 44 47,這不在字典中,但代碼仍然會返回「.PDF」,因爲它們非常相似。
任何幫助,以及任何建議,因爲我是非常新的Python和編程一般。
「最相似的值」< - 定義? – timgeb
其中「最相似的值」是一個僅相差2-3個字節的密鑰。 即,如果FF D8 EE 00不匹配,則返回FF D9 EE 00作爲可能的結果。 –
不是很清楚要問什麼。 –