【发布时间】:2021-02-23 02:30:36
【问题描述】:
对于我正在进行的网络抓取项目,我计划将实体存储在数据库中,其中它们的 ID 是其名称/标题的 md5 哈希。
但是,由于字符串中存在 Unicode,相同名称/标题的不同哈希值将存在
例如,“Kinesiology, Phys Ed\xa0and Recreation”的 md5 哈希值将不同于“Kinesiology, Phys Ed and Recreation”。
我尝试使用 Unicode 规范化,但哈希之间的差异仍然相同
import hashlib
import unicodedata
def generate_id(*args):
"""
:param args: strings to be used to generate an id
:return: md5 hash of the passed arguments
"""
string = ''
for arg in args:
string += ' ' + arg
hash_algorithm = hashlib.md5()
hash_algorithm.update(string.encode('utf-8'))
return hash_algorithm.hexdigest()
def clean_text(text):
"""
normalizes the unicode in a text to be more readable and generate a more accurate id from
:param text: string to be normalized
:return: normalized version of text
"""
return unicodedata.normalize('NFC', text)
print(generate_id(clean_text('Kinesiology, Phys Ed\xa0and Recreation'))) # hashes to acd21f3b094a77d1a2393a8daeac42d9
print(generate_id('Kinesiology, Phys Ed and Recreation')) # hashes to 5ac6bc3ca3d743d99e9b93a7a5379fe9
我能做些什么来确保两个字符串相同并且散列到相同的 id 使得“Kinesiology, Phys Ed\xa0and Recreation”与“Kinesiology, Phys Ed and Recreation”是相同的字符串和相同的散列(无论 unicode 是否存在,任何 2 个字符串都一样)?
【问题讨论】:
标签: python unicode hash md5 python-unicode