在Python中哈希字符串

2024-04-20 09:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个数据集,它有一个users social security#(不带破折号),我想用它作为唯一的id,但是为了保护用户的身份,我想对字符串进行散列(md5)。以下是数据集示例:

 id        |     date     |     sale_id
 543875600    2014-03-22        a4395

希望输出如下或类似:

 id                               |     date     |     sale_id
 762be25b5c6eb20dd6c791840c01aa33    2014-03-22        a4395

我想用python来解决这个问题,因为我目前正在用python和数据来聚合目录中的许多文件,所以这将是额外的代码,我将在下面的代码中包括这些代码:

 import glob
 files = glob.glob( '*.csv' )
 output="combined.csv"

 with open(output, 'w' ) as result:
      for thefile in files:
          f = [open(thefile).read()]
          for line in f:
              result.write( line )
  message = 'file created'
  print (message) 

Tags: csv数据代码inidforoutputdate
2条回答

先回答技术问题。。。你知道吗

反转字符串-可读方式:

>>> s = "abcde"
>>> "".join(reversed(s))
'edcba'

反转字符串-可读性较差的方式:

>>> s = "abcde"
>>> s[::-1]
'edcba'

“扰乱”字符串:

>>> import random
>>> l = list(s)
>>> random.shuffle(l)
>>> "".join(l)
'dacbe'

现在chrisarena和Zlopez是对的:两者都不是有效的“保护”,你真的想散列你的id。你知道吗

>>> import hashlib
>>> id = "000000000"
>>> my_hash = hashlib.sha224(id).hexdigest()
>>> my_hash
'c34c462b2fb1982287dc9df575c03669b308301dbc3be6d62dd83536'

当然,如果您确实需要md5,也可以使用库中的any other hash function。你知道吗

相关问题 更多 >