From 4e8d7e4bcb0eeb49f6df38b530eb39c6cf953874 Mon Sep 17 00:00:00 2001 From: Arthur de Jong Date: Tue, 20 Sep 2011 21:14:48 +0000 Subject: implement a conversion function from ISBN13 to ISBN10 git-svn-id: http://arthurdejong.org/svn/python-stdnum/python-stdnum@80 9dea7c4f-944c-4273-ac1a-574ede026edc --- stdnum/isbn.py | 24 ++++++++++++++++++++++++ tests/test_isbn.doctest | 20 ++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/stdnum/isbn.py b/stdnum/isbn.py index 382b13d..59262ba 100644 --- a/stdnum/isbn.py +++ b/stdnum/isbn.py @@ -37,6 +37,8 @@ False 'ISBN13' >>> to_isbn13('1-85798-218-5') '978-1-85798-218-3' +>>> to_isbn10('978-1-85798-218-3') +'1-85798-218-5' """ from stdnum import ean @@ -111,6 +113,28 @@ def to_isbn13(number): return '978' + number +def to_isbn10(number): + """Convert the number to ISBN-13 format.""" + number = number.strip() + min_number = compact(number) + if len(min_number) == 10: + return number # nothing to do, already ISBN-13 + elif isbn_type(min_number) != 'ISBN13': + raise ValueError('Not a valid ISBN13.') + elif not number.startswith('978'): + raise ValueError('Does not use 978 Bookland prefix.') + # strip EAN prefix + number = number[3:-1].strip().strip('-') + digit = _calc_isbn10_check_digit(min_number[3:-1]) + # append the new check digit + if ' ' in number: + return number + ' ' + digit + elif '-' in number: + return number + '-' + digit + else: + return number + digit + + def split(number, convert=False): """Split the specified ISBN into an EAN.UCC prefix, a group prefix, a registrant, an item number and a check-digit. If the number is in ISBN-10 diff --git a/tests/test_isbn.doctest b/tests/test_isbn.doctest index f84c3fc..e759114 100644 --- a/tests/test_isbn.doctest +++ b/tests/test_isbn.doctest @@ -51,6 +51,26 @@ True '9781857982183' +See if ISBN13 to 10 conversion works. + +>>> isbn.to_isbn10('1-85798-218-5') # ISBN10 should stay ISBN10 +'1-85798-218-5' +>>> isbn.to_isbn10('978 1 85798218 3') +'1 85798218 5' +>>> isbn.to_isbn10('9781857982183') +'1857982185' +>>> isbn.to_isbn10('978-1-85798-218-3') +'1-85798-218-5' +>>> isbn.to_isbn10('979-20-1234567-8') # incorrect check digit +Traceback (most recent call last): + ... +ValueError: Not a valid ISBN13. +>>> isbn.to_isbn10('9791843123391') +Traceback (most recent call last): + ... +ValueError: Does not use 978 Bookland prefix. + + Regrouping tests. >>> isbn.split('9024538270') # normal ISBN10 -- cgit v1.2.3