1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
9 from librarian.dcparser import Person
12 def _register_function(f):
13 """ Register extension function with lxml """
14 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
15 ns[f.__name__] = lambda context, *args: f(*args)
18 ENTITY_SUBSTITUTIONS = [
27 def substitute_entities(text):
28 """XPath extension function converting all entites in passed text."""
29 if isinstance(text, list):
31 for entity, substitutution in ENTITY_SUBSTITUTIONS:
32 text = text.replace(entity, substitutution)
36 def reg_substitute_entities():
37 _register_function(substitute_entities)
41 """Remove unneeded whitespace from beginning and end"""
42 if isinstance(text, list):
44 return re.sub(r'\s+', ' ', text).strip()
48 _register_function(strip)
51 def starts_white(text):
52 if isinstance(text, list):
56 return text[0].isspace()
59 def reg_starts_white():
60 _register_function(starts_white)
65 if isinstance(text, list):
69 return text[-1].isspace()
70 _register_function(ends_white)
73 def wrap_words(text, wrapping):
74 """XPath extension function automatically wrapping words in passed text"""
75 if isinstance(text, list):
80 words = re.split(r'\s', text)
85 line_length += len(word) + 1
86 if line_length > wrapping:
87 # Max line length was exceeded. We create new line
89 line_length = len(word)
90 lines[-1].append(word)
91 return '\n'.join(' '.join(line) for line in lines)
95 _register_function(wrap_words)
98 def person_name(text):
99 """ Converts "Name, Forename" to "Forename Name" """
100 if isinstance(text, list):
102 return Person.from_text(text).readable()
105 def reg_person_name():
106 _register_function(person_name)
109 def texcommand(text):
110 """Remove non-letters"""
111 if isinstance(text, list):
113 return re.sub(r'[^a-zA-Z]', '', text).strip()
116 def reg_texcommand():
117 _register_function(texcommand)
120 def reg_get(format_):
124 if hasattr(obj, arg):
125 obj = getattr(obj, arg)
129 except (TypeError, KeyError), e:
130 # Just raise proper AttributeError.
133 _register_function(get)