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
11 def _register_function(f):
12 """ Register extension function with lxml """
13 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
17 ENTITY_SUBSTITUTIONS = [
25 def substitute_entities(context, text):
26 """XPath extension function converting all entites in passed text."""
27 if isinstance(text, list):
29 for entity, substitutution in ENTITY_SUBSTITUTIONS:
30 text = text.replace(entity, substitutution)
34 def reg_substitute_entities():
35 _register_function(substitute_entities)
38 def strip(context, text):
39 """Remove unneeded whitespace from beginning and end"""
40 if isinstance(text, list):
42 return re.sub(r'\s+', ' ', text).strip()
46 _register_function(strip)
49 def starts_white(context, text):
50 if isinstance(text, list):
54 return text[0].isspace()
57 def reg_starts_white():
58 _register_function(starts_white)
62 def ends_white(context, text):
63 if isinstance(text, list):
67 return text[-1].isspace()
68 _register_function(ends_white)
71 def wrap_words(context, text, wrapping):
72 """XPath extension function automatically wrapping words in passed text"""
73 if isinstance(text, list):
78 words = re.split(r'\s', text)
83 line_length += len(word) + 1
84 if line_length > wrapping:
85 # Max line length was exceeded. We create new line
87 line_length = len(word)
88 lines[-1].append(word)
89 return '\n'.join(' '.join(line) for line in lines)
93 _register_function(wrap_words)
96 def person_name(context, text):
97 """ Converts "Name, Forename" to "Forename Name" """
98 if isinstance(text, list):
100 return Person.from_text(text).readable()
103 def reg_person_name():
104 _register_function(person_name)
107 def texcommand(context, text):
108 """Remove non-letters"""
109 if isinstance(text, list):
111 return re.sub(r'[^a-zA-Z]', '', text).strip()
114 def reg_texcommand():
115 _register_function(texcommand)
118 def reg_get(format_):
119 def get(context, *args):
122 if hasattr(obj, arg):
123 obj = getattr(obj, arg)
127 except (TypeError, KeyError), e:
128 # Just raise proper AttributeError.
131 _register_function(get)