1. 程式人生 > 實用技巧 >[Python學習筆記-010]身份證驗證演算法及Python實現

[Python學習筆記-010]身份證驗證演算法及Python實現

01 - 身份證驗證演算法

XXX

02 - Python實現

 1 #!/usr/bin/python3
 2 """ A simple utility to validate ID for Chinese
 3 
 4     References:
 5     o https://jingyan.baidu.com/article/ff4116259e0a7112e48237b9.html
 6     o https://www.cnblogs.com/xudong-bupt/p/3293838.html
 7 """
 8 
 9 import sys
10 
11 
12 def get_verification_code(id17):
13 l_wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] 14 l_vc = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'] 15 s = 0 16 for i in range(len(l_wi)): 17 s += l_wi[i] * int(id17[i]) 18 m = s % 11 19 return l_vc[m] 20 21 22 def is_valid_id(cn_id): 23 cn_id_17 = cn_id[0:-1]
24 vc = get_verification_code(cn_id_17) 25 if vc != cn_id[-1]: 26 print("Oops, invalid ID #<<< should be %s%s" % (cn_id_17, vc), 27 file=sys.stderr) 28 return False 29 return True 30 31 32 def main(argc, argv): 33 if argc != 2: 34 print
("Usage: %s <ID>" % argv[0], file=sys.stderr) 35 print("e.g.", file=sys.stderr) 36 print(" %s 51023519890708911X" % argv[0], file=sys.stderr) 37 return 1 38 39 cn_id = argv[1] 40 if len(cn_id) != 18: 41 print("-FAIL, invalid ID as its length is not 18", file=sys.stderr) 42 return 1 43 44 if not is_valid_id(cn_id): 45 print("-FAIL", file=sys.stderr) 46 return 1 47 print("+OK") 48 return 0 49 50 51 if __name__ == '__main__': 52 sys.exit(main(len(sys.argv), sys.argv))

執行樣例:

huanli@idorax16:~$ ./validate_id.py 510235198907089112
Oops, invalid ID #<<< should be 51023519890708911X
-FAIL
huanli@idorax16:~$ ./validate_id.py 51023519890708911X
+OK

參考資料: