85e41534b9fc3514d2e89419190c64cef0e24d07
[wolnelektury.git] / lib / dcparser / converters.py
1 # -*- coding: utf-8 -*-
2 from datetime import date
3 import time
4 import re
5
6
7 class Person(object):
8     """Single person with last name and a list of first names."""
9     def __init__(self, last_name, *first_names):
10         self.last_name = last_name
11         self.first_names = first_names
12     
13     
14     def __eq__(self, right):
15         return self.last_name == right.last_name and self.first_names == right.first_names
16     
17     
18     def __unicode__(self):
19         if len(self.first_names) > 0:
20             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
21         else:
22             return self.last_name
23     
24     
25     def __repr__(self):
26         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
27
28
29 def str_to_unicode(value, previous):
30     return unicode(value)
31
32
33 def str_to_unicode_list(value, previous):
34     if previous is None:
35         previous = []
36     previous.append(str_to_unicode(value))
37     return previous
38
39
40 def str_to_person(value, previous):
41     comma_count = value.count(',')
42     
43     if comma_count == 0:
44         last_name, first_names = value, []
45     elif comma_count == 1:
46         last_name, first_names = value.split(',')
47         first_names = [name for name in first_names.split(' ') if len(name)]
48     else:
49         raise ValueError("value contains more than one comma: %r" % value)
50     
51     return Person(last_name.strip(), *first_names)
52
53
54 def str_to_date(value, previous):
55     try:
56         t = time.strptime(value, '%Y-%m-%d')
57     except ValueError:
58         t = time.strptime(value, '%Y')
59     return date(t[0], t[1], t[2])
60
61