Created
February 25, 2014 19:22
-
-
Save hagope/9215793 to your computer and use it in GitHub Desktop.
convert isbn10 to isbn13 and accounts for 8,9 digit isbn without leading zeroes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def check_digit_10(isbn): | |
assert len(isbn) == 9 | |
sum = 0 | |
for i in range(len(isbn)): | |
c = int(isbn[i]) | |
w = i + 1 | |
sum += w * c | |
r = sum % 11 | |
if r == 10: return 'X' | |
else: return str(r) | |
def check_digit_13(isbn): | |
assert len(isbn) == 12 | |
sum = 0 | |
for i in range(len(isbn)): | |
c = int(isbn[i]) | |
if i % 2: w = 3 | |
else: w = 1 | |
sum += w * c | |
r = 10 - (sum % 10) | |
if r == 10: return '0' | |
else: return str(r) | |
def convert_10_to_13(isbn): | |
char_len = len(isbn) | |
if char_len == 13: | |
return isbn | |
elif char_len == 8: | |
prefix = '97800' + isbn[:-1] | |
check = check_digit_13(prefix) | |
return prefix + check | |
elif char_len == 9: | |
prefix = '9780' + isbn[:-1] | |
check = check_digit_13(prefix) | |
return prefix + check | |
elif char_len == 10: | |
prefix = '978' + isbn[:-1] | |
check = check_digit_13(prefix) | |
return prefix + check | |
fname = 'isbns.txt' | |
with open(fname) as f: | |
isbns = f.readlines() | |
for isbn in isbns: | |
print convert_10_to_13(isbn.rstrip().lstrip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment