Browse Source

Début de la mise à niveau pep8 (#4)

pull/3/head
Luthaf 11 years ago
parent
commit
fa948b7186
  1. 31
      songbook.py
  2. 19
      songbook/authors.py
  3. 39
      songbook/build.py
  4. 2
      songbook/files.py
  5. 62
      songbook/index.py
  6. 2
      songbook/plastex-songs.py
  7. 12
      songbook/plastex.py
  8. 20
      songbook/songs.py

31
songbook.py

@ -12,6 +12,7 @@ import sys
from songbook.build import buildsongbook from songbook.build import buildsongbook
from songbook import __VERSION__ from songbook import __VERSION__
def argument_parser(args): def argument_parser(args):
parser = argparse.ArgumentParser(description="A song book compiler") parser = argparse.ArgumentParser(description="A song book compiler")
@ -24,34 +25,38 @@ def argument_parser(args):
parser.add_argument('--datadir', '-d', nargs=1, type=str, action='store', parser.add_argument('--datadir', '-d', nargs=1, type=str, action='store',
help=textwrap.dedent("""\ help=textwrap.dedent("""\
Data location. Expected (not necessarily required) subdirectories are 'songs', 'img', 'latex', 'templates'. Data location. Expected (not necessarily required)
subdirectories are 'songs', 'img', 'latex', 'templates'.
""")) """))
options = parser.parse_args(args) options = parser.parse_args(args)
return options return options
def main(): def main():
locale.setlocale(locale.LC_ALL, '') # set script locale to match user's # set script locale to match user's
locale.setlocale(locale.LC_ALL, '')
options = argument_parser(sys.argv[1:]) options = argument_parser(sys.argv[1:])
sbFile = options.book[0] songbook_path = options.book[0]
basename = os.path.basename(sbFile)[:-3] basename = os.path.basename(songbook_path)[:-3]
f = open(sbFile) with open(songbook_path) as songbook_file:
sb = json.load(f) songbook = json.load(songbook_file)
f.close()
if options.datadir is not None: if options.datadir is not None:
sb['datadir'] = options.datadir songbook['datadir'] = options.datadir
elif 'datadir' in sb.keys(): elif 'datadir' in songbook.keys():
if not os.path.isabs(sb['datadir']): if not os.path.isabs(songbook['datadir']):
sb['datadir'] = os.path.join(os.path.dirname(sbFile), sb['datadir']) songbook['datadir'] = os.path.join(os.path.dirname(songbook_path),
songbook['datadir']
)
else: else:
sb['datadir'] = os.path.dirname(sbFile) songbook['datadir'] = os.path.dirname(songbook_path)
buildsongbook(sb, basename) buildsongbook(songbook, basename)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

19
songbook/authors.py

@ -1,6 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def split_author_names(string): def split_author_names(string):
"""Split author between first and last name. """Split author between first and last name.
@ -30,6 +31,7 @@ def split_author_names(string):
brace_count -= 1 brace_count -= 1
return string[:last_space], string[last_space:] return string[:last_space], string[last_space:]
def split_sep_author(string, sep): def split_sep_author(string, sep):
authors = [] authors = []
match = sep.match(string) match = sep.match(string)
@ -40,12 +42,16 @@ def split_sep_author(string, sep):
authors.append(string) authors.append(string)
return authors return authors
def processauthors(authors_string, after = [], ignore = [], sep = []):
def processauthors(authors_string, after=[], ignore=[], sep=[]):
"""Return a list of authors """Return a list of authors
For example, we are processing: For example, we are processing:
# processauthors( # processauthors(
# "Lyrics by William Blake (from Milton, 1808), music by Hubert Parry (1916), and sung by The Royal\ Choir~of~Nowhere (just here to show you how processing is done)", # "Lyrics by William Blake (from Milton, 1808),
music by Hubert Parry (1916),
and sung by The Royal\ Choir~of~Nowhere
(just here to show you how processing is done)",
# after = ["by"], # after = ["by"],
# ignore = ["anonymous"], # ignore = ["anonymous"],
# sep = ["and"] # sep = ["and"]
@ -54,10 +60,12 @@ def processauthors(authors_string, after = [], ignore = [], sep = []):
The "authors_string" string is processed as: The "authors_string" string is processed as:
1) First, parenthesis (and its content) are removed. 1) First, parenthesis (and its content) are removed.
# "Lyrics by William Blake, music by Hubert Parry, and sung by The Royal\ Choir~of~Nowhere" # "Lyrics by William Blake, music by Hubert Parry,
and sung by The Royal\ Choir~of~Nowhere"
2) String is split, separators being comma and words from "sep". 2) String is split, separators being comma and words from "sep".
# ["Lyrics by William Blake", "music by Hubert Parry", "sung by The Royal\ Choir~of~Nowhere"] # ["Lyrics by William Blake", "music by Hubert Parry",
"sung by The Royal\ Choir~of~Nowhere"]
3) Everything before words in "after" is removed. 3) Everything before words in "after" is removed.
# ["William Blake", "Hubert Parry", "The Royal\ Choir~of~Nowhere"] # ["William Blake", "Hubert Parry", "The Royal\ Choir~of~Nowhere"]
@ -113,7 +121,8 @@ def processauthors(authors_string, after = [], ignore = [], sep = []):
authors_list = dest authors_list = dest
# Cleaning: removing empty authors and unnecessary spaces # Cleaning: removing empty authors and unnecessary spaces
authors_list = [author.lstrip() for author in authors_list if author.lstrip()] authors_list = [author.lstrip()
for author in authors_list if author.lstrip()]
# Moving first names after last names # Moving first names after last names
dest = [] dest = []

39
songbook/build.py

@ -14,17 +14,19 @@ from songbook.index import processSXD
from songbook.songs import Song, SongsList from songbook.songs import Song, SongsList
from songbook import __SHAREDIR__ from songbook import __SHAREDIR__
def parseTemplate(template): def parseTemplate(template):
embeddedJsonPattern = re.compile(r"^%%:") embeddedJsonPattern = re.compile(r"^%%:")
f = open(template) with open(template) as template_file:
code = [ line[3:-1] for line in f if embeddedJsonPattern.match(line) ] code = [line[3:-1] for line in template_file if embeddedJsonPattern.match(line)]
f.close()
data = json.loads(''.join(code)) data = json.loads(''.join(code))
parameters = dict() parameters = dict()
for param in data: for param in data:
parameters[param["name"]] = param parameters[param["name"]] = param
return parameters return parameters
def toValue(parameter, data): def toValue(parameter, data):
if "type" not in parameter: if "type" not in parameter:
return data return data
@ -37,7 +39,7 @@ def toValue(parameter, data):
elif parameter["type"] == "color": elif parameter["type"] == "color":
return data[1:] return data[1:]
elif parameter["type"] == "font": elif parameter["type"] == "font":
return data+'pt' return data + 'pt'
elif parameter["type"] == "enum": elif parameter["type"] == "enum":
return data return data
elif parameter["type"] == "file": elif parameter["type"] == "file":
@ -49,15 +51,20 @@ def toValue(parameter, data):
joinText = '' joinText = ''
return joinText.join(data) return joinText.join(data)
def formatDeclaration(name, parameter): def formatDeclaration(name, parameter):
value = "" value = ""
if "default" in parameter: if "default" in parameter:
value = parameter["default"] value = parameter["default"]
return '\\def\\set@{name}#1{{\\def\\get{name}{{#1}}}}\n'.format(name=name) + formatDefinition(name, toValue(parameter, value)) return ('\\def\\set@{name}#1{{\\def\\get{name}{{#1}}}}\n'.format(name=name)
+ formatDefinition(name, toValue(parameter, value))
)
def formatDefinition(name, value): def formatDefinition(name, value):
return '\\set@{name}{{{value}}}\n'.format(name=name, value=value) return '\\set@{name}{{{value}}}\n'.format(name=name, value=value)
def clean(basename): def clean(basename):
generated_extensions = [ generated_extensions = [
"_auth.sbx", "_auth.sbx",
@ -76,6 +83,7 @@ def clean(basename):
return True return True
def makeTexFile(sb, output): def makeTexFile(sb, output):
datadir = sb['datadir'] datadir = sb['datadir']
name = output[:-4] name = output[:-4]
@ -117,10 +125,12 @@ def makeTexFile(sb, output):
authwords_tex += "\\auth%sword{%s}\n" % (key, word) authwords_tex += "\\auth%sword{%s}\n" % (key, word)
sb["authwords"] = authwords_tex sb["authwords"] = authwords_tex
if "after" in authwords: if "after" in authwords:
authwords["after"] = [re.compile(r"^.*%s\b(.*)" % after) for after in authwords["after"]] authwords["after"] = [re.compile(r"^.*%s\b(.*)" % after)
for after in authwords["after"]]
if "sep" in authwords: if "sep" in authwords:
authwords["sep"] = [" %s" % sep for sep in authwords["sep"]] + [","] authwords["sep"] = [" %s" % sep for sep in authwords["sep"]] + [","]
authwords["sep"] = [re.compile(r"^(.*)%s (.*)$" % sep) for sep in authwords["sep"] ] authwords["sep"] = [re.compile(r"^(.*)%s (.*)$" % sep)
for sep in authwords["sep"]]
if "lang" not in sb: if "lang" not in sb:
sb["lang"] = "french" sb["lang"] = "french"
@ -152,15 +162,15 @@ def makeTexFile(sb, output):
out.write('%% This file has been automatically generated, do not edit!\n') out.write('%% This file has been automatically generated, do not edit!\n')
out.write('\\makeatletter\n') out.write('\\makeatletter\n')
# output automatic parameters # output automatic parameters
out.write(formatDeclaration("name", {"default":name})) out.write(formatDeclaration("name", {"default": name}))
out.write(formatDeclaration("songslist", {"type":"stringlist"})) out.write(formatDeclaration("songslist", {"type": "stringlist"}))
# output template parameter command # output template parameter command
for name, parameter in parameters.iteritems(): for name, parameter in parameters.iteritems():
out.write(formatDeclaration(name, parameter)) out.write(formatDeclaration(name, parameter))
# output template parameter values # output template parameter values
for name, value in sb.iteritems(): for name, value in sb.iteritems():
if name in parameters: if name in parameters:
out.write(formatDefinition(name, toValue(parameters[name],value))) out.write(formatDefinition(name, toValue(parameters[name], value)))
if len(songs) > 0: if len(songs) > 0:
out.write(formatDefinition('songslist', songslist.latex())) out.write(formatDefinition('songslist', songslist.latex()))
@ -169,7 +179,7 @@ def makeTexFile(sb, output):
# output template # output template
commentPattern = re.compile(r"^\s*%") commentPattern = re.compile(r"^\s*%")
with codecs.open(os.path.join(template_dir, template), 'r', 'utf-8') as f: with codecs.open(os.path.join(template_dir, template), 'r', 'utf-8') as f:
content = [ line for line in f if not commentPattern.match(line) ] content = [line for line in f if not commentPattern.match(line)]
for index, line in enumerate(content): for index, line in enumerate(content):
if re.compile("getDataImgDirectory").search(line): if re.compile("getDataImgDirectory").search(line):
@ -183,6 +193,7 @@ def makeTexFile(sb, output):
out.write(u''.join(content)) out.write(u''.join(content))
out.close() out.close()
def buildsongbook(sb, basename): def buildsongbook(sb, basename):
"""Build a songbook """Build a songbook
@ -191,12 +202,12 @@ def buildsongbook(sb, basename):
- basename: basename of the songbook to be built. - basename: basename of the songbook to be built.
""" """
texFile = basename + ".tex" texFile = basename + ".tex"
# Make TeX file # Make TeX file
makeTexFile(sb, texFile) makeTexFile(sb, texFile)
if not os.environ.has_key('TEXINPUTS'): if not 'TEXINPUTS' in os.environ.keys():
os.environ['TEXINPUTS'] = '' os.environ['TEXINPUTS'] = ''
os.environ['TEXINPUTS'] += os.pathsep + os.path.join(__SHAREDIR__, 'latex') os.environ['TEXINPUTS'] += os.pathsep + os.path.join(__SHAREDIR__, 'latex')
os.environ['TEXINPUTS'] += os.pathsep + os.path.join(sb['datadir'], 'latex') os.environ['TEXINPUTS'] += os.pathsep + os.path.join(sb['datadir'], 'latex')
@ -210,7 +221,7 @@ def buildsongbook(sb, basename):
for sxdFile in sxdFiles: for sxdFile in sxdFiles:
print "processing " + sxdFile print "processing " + sxdFile
idx = processSXD(sxdFile) idx = processSXD(sxdFile)
indexFile = open(sxdFile[:-3]+"sbx", "w") indexFile = open(sxdFile[:-3] + "sbx", "w")
indexFile.write(idx.entriesToStr().encode('utf8')) indexFile.write(idx.entriesToStr().encode('utf8'))
indexFile.close() indexFile.close()

2
songbook/files.py

@ -5,10 +5,10 @@
import fnmatch import fnmatch
import os import os
def recursiveFind(root_directory, pattern): def recursiveFind(root_directory, pattern):
matches = [] matches = []
for root, dirnames, filenames in os.walk(root_directory): for root, dirnames, filenames in os.walk(root_directory):
for filename in fnmatch.filter(filenames, pattern): for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename)) matches.append(os.path.join(root, filename))
return matches return matches

62
songbook/index.py

@ -13,7 +13,7 @@ from unidecode import unidecode
import locale import locale
import re import re
import sys import sys
import warnings #import warnings
from songbook.authors import processauthors from songbook.authors import processauthors
from songbook.plastex import simpleparse from songbook.plastex import simpleparse
@ -22,6 +22,7 @@ from songbook.plastex import simpleparse
keywordPattern = re.compile(r"^%(\w+)\s?(.*)$") keywordPattern = re.compile(r"^%(\w+)\s?(.*)$")
firstLetterPattern = re.compile(r"^(?:\{?\\\w+\}?)*[^\w]*(\w)") firstLetterPattern = re.compile(r"^(?:\{?\\\w+\}?)*[^\w]*(\w)")
def sortkey(value): def sortkey(value):
''' '''
From a title, return something usable for sorting. It handles locale (but From a title, return something usable for sorting. It handles locale (but
@ -30,35 +31,40 @@ def sortkey(value):
''' '''
return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A'))) return locale.strxfrm(unidecode(simpleparse(value).replace(' ', 'A')))
def processSXDEntry(tab): def processSXDEntry(tab):
return (tab[0], tab[1], tab[2]) return (tab[0], tab[1], tab[2])
def processSXD(filename): def processSXD(filename):
file = open(filename) index_file = open(filename)
data = [] data = []
for line in file: for line in index_file:
data.append(line.strip()) data.append(line.strip())
file.close() index_file.close()
i = 1 i = 1
idx = index(data[0]) idx = index(data[0])
while len(data) > i and data[i].startswith('%'): while len(data) > i and data[i].startswith('%'):
keywords = keywordPattern.match(data[i]).groups() keywords = keywordPattern.match(data[i]).groups()
idx.keyword(keywords[0],keywords[1]) idx.keyword(keywords[0], keywords[1])
i += 1 i += 1
idx.compileKeywords() idx.compileKeywords()
for i in range(i,len(data),3): for i in range(i, len(data), 3):
entry = processSXDEntry(data[i:i+3]) entry = processSXDEntry(data[i:i + 3])
idx.add(entry[0],entry[1],entry[2]) idx.add(entry[0], entry[1], entry[2])
return idx return idx
class index: class index:
def __init__(self, indextype): def __init__(self, indextype):
self.data = dict() self.data = dict()
self.keywords = dict() self.keywords = dict()
self.prefix_patterns = []
self.authwords = {"after": [], "ignore": [], "sep": []}
if indextype == "TITLE INDEX DATA FILE": if indextype == "TITLE INDEX DATA FILE":
self.indextype = "TITLE" self.indextype = "TITLE"
elif indextype == "SCRIPTURE INDEX DATA FILE": elif indextype == "SCRIPTURE INDEX DATA FILE":
@ -70,23 +76,21 @@ class index:
def filter(self, key): def filter(self, key):
letter = firstLetterPattern.match(key).group(1) letter = firstLetterPattern.match(key).group(1)
if re.match('\d',letter): if re.match('\d', letter):
letter = '0-9' letter = '0-9'
return (letter.upper(), key) return (letter.upper(), key)
def keyword(self, key, word): def keyword(self, key, word):
if not self.keywords.has_key(key): if not key in self.keywords.keys():
self.keywords[key] = [] self.keywords[key] = []
self.keywords[key].append(word) self.keywords[key].append(word)
def compileKeywords(self): def compileKeywords(self):
self.prefix_patterns = []
if self.indextype == "TITLE": if self.indextype == "TITLE":
if 'prefix' in self.keywords: if 'prefix' in self.keywords:
for prefix in self.keywords['prefix']: for prefix in self.keywords['prefix']:
self.prefix_patterns.append(re.compile(r"^(%s)(\b|\\)(\s*.*)$" % prefix)) self.prefix_patterns.append(re.compile(r"^(%s)(\b|\\)(\s*.*)$" % prefix))
self.authwords = {"after": [], "ignore": [], "sep": []}
if self.indextype == "AUTHOR": if self.indextype == "AUTHOR":
for key in self.keywords: for key in self.keywords:
if key in self.authwords: if key in self.authwords:
@ -94,20 +98,22 @@ class index:
for word in self.authwords.keys(): for word in self.authwords.keys():
if word in self.keywords: if word in self.keywords:
if word == "after": if word == "after":
self.authwords[word] = [re.compile(r"^.*%s\b(.*)" % after) for after in self.keywords[word]] self.authwords[word] = [re.compile(r"^.*%s\b(.*)" % after)
for after in self.keywords[word]]
elif word == "sep": elif word == "sep":
self.authwords[word] = [" %s" % sep for sep in self.authwords[word]] + [","] self.authwords[word] = [" %s" % sep for sep in self.authwords[word]] + [","]
self.authwords[word] = [re.compile(r"^(.*)%s (.*)$" % sep) for sep in self.authwords[word] ] self.authwords[word] = [re.compile(r"^(.*)%s (.*)$" % sep)
for sep in self.authwords[word]]
else: else:
self.authwords[word] = self.keywords[word] self.authwords[word] = self.keywords[word]
def _raw_add(self, key, number, link): def _raw_add(self, key, number, link):
(first, key) = self.filter(key) (first, key) = self.filter(key)
if not self.data.has_key(first): if not first in self.data.keys():
self.data[first] = dict() self.data[first] = dict()
if not self.data[first].has_key(key): if not key in self.data[first].keys():
self.data[first][key] = [] self.data[first][key] = []
self.data[first][key].append({'num':number, 'link':link}) self.data[first][key].append({'num': number, 'link': link})
def add(self, key, number, link): def add(self, key, number, link):
if self.indextype == "TITLE": if self.indextype == "TITLE":
@ -116,8 +122,8 @@ class index:
match = pattern.match(key) match = pattern.match(key)
if match: if match:
self._raw_add( self._raw_add(
"%s (%s)" % (match.group(2) + match.group(3), match.group(1)), "%s (%s)" % (match.group(2) + match.group(3),
number, link) match.group(1)), number, link)
return return
self._raw_add(key, number, link) self._raw_add(key, number, link)
@ -129,26 +135,26 @@ class index:
self._raw_add(author, number, link) self._raw_add(author, number, link)
def refToStr(self, ref): def refToStr(self, ref):
if sys.version_info >= (2,6): if sys.version_info >= (2, 6):
return '\\hyperlink{{{0[link]}}}{{{0[num]}}}'.format(ref) return '\\hyperlink{{{0[link]}}}{{{0[num]}}}'.format(ref)
else: else:
return '\\hyperlink{%(link)s}{%(num)s}' % ref return '\\hyperlink{%(link)s}{%(num)s}' % ref
def entryToStr(self, key, entry): def entryToStr(self, key, entry):
if sys.version_info >= (2,6): if sys.version_info >= (2, 6):
return unicode('\\idxentry{{{0}}}{{{1}}}\n').format(key, '\\\\'.join(map(self.refToStr, entry))) return unicode('\\idxentry{{{0}}}{{{1}}}\n').format(key, '\\\\'.join(map(self.refToStr, entry)))
else: else:
return unicode('\\idxentry{%s}{%s}\n') % (key, '\\\\'.join(map(self.refToStr, entry))) return unicode('\\idxentry{%s}{%s}\n') % (key, '\\\\'.join(map(self.refToStr, entry)))
def idxBlockToStr(self, letter, entries): def idxBlockToStr(self, letter, entries):
str = '\\begin{idxblock}{'+letter+'}'+'\n' string = '\\begin{idxblock}{' + letter + '}' + '\n'
for key in sorted(entries.keys(), key=sortkey): for key in sorted(entries.keys(), key=sortkey):
str += self.entryToStr(key, entries[key]) string += self.entryToStr(key, entries[key])
str += '\\end{idxblock}'+'\n' string += '\\end{idxblock}' + '\n'
return str return string
def entriesToStr(self): def entriesToStr(self):
str = "" string = ""
for letter in sorted(self.data.keys()): for letter in sorted(self.data.keys()):
str += self.idxBlockToStr(letter, self.data[letter]) string += self.idxBlockToStr(letter, self.data[letter])
return str return string

2
songbook/plastex-songs.py

@ -5,6 +5,7 @@ import plasTeX
from songbook.plastex import processUnbreakableSpace from songbook.plastex import processUnbreakableSpace
def split_linebreak(texlist): def split_linebreak(texlist):
return_list = [] return_list = []
current = [] current = []
@ -18,6 +19,7 @@ def split_linebreak(texlist):
return_list.append(current) return_list.append(current)
return return_list return return_list
class beginsong(plasTeX.Command): class beginsong(plasTeX.Command):
args = '{titles}[ args:dict ]' args = '{titles}[ args:dict ]'
def invoke(self, tex): def invoke(self, tex):

12
songbook/plastex.py

@ -5,23 +5,27 @@ from plasTeX.TeX import TeX
from plasTeX.Base.LaTeX import Sentences from plasTeX.Base.LaTeX import Sentences
import codecs import codecs
import copy #import copy
import locale import locale
import os import os
import sys import sys
def processUnbreakableSpace(node): def processUnbreakableSpace(node):
"""Replace '~' and '\ ' in node by nodes that will be rendered as unbreakable space. """Replace '~' and '\ ' in node by nodes that
will be rendered as unbreakable space.
Return node object for convenience. Return node object for convenience.
""" """
if type(node) == Sentences.InterWordSpace or (type(node) == Sentences.NoLineBreak and node.source == '~ '): if (type(node) == Sentences.InterWordSpace or
(type(node) == Sentences.NoLineBreak and node.source == '~ ')):
node.unicode = unichr(160) node.unicode = unichr(160)
for child in node.childNodes: for child in node.childNodes:
processUnbreakableSpace(child) processUnbreakableSpace(child)
return node return node
def simpleparse(text): def simpleparse(text):
"""Parse a simple LaTeX string. """Parse a simple LaTeX string.
""" """
@ -30,6 +34,7 @@ def simpleparse(text):
doc = tex.parse() doc = tex.parse()
return processUnbreakableSpace(doc.textContent) return processUnbreakableSpace(doc.textContent)
class SongParser: class SongParser:
"""Analyseur syntaxique de fichiers .sg""" """Analyseur syntaxique de fichiers .sg"""
@ -50,6 +55,7 @@ class SongParser:
tex.input(codecs.open(filename, 'r+', 'utf-8', 'replace')) tex.input(codecs.open(filename, 'r+', 'utf-8', 'replace'))
return tex.parse() return tex.parse()
def parsetex(filename): def parsetex(filename):
"""Analyse syntaxique d'un fichier .sg """Analyse syntaxique d'un fichier .sg

20
songbook/songs.py

@ -10,6 +10,7 @@ import re
from songbook.authors import processauthors from songbook.authors import processauthors
from songbook.plastex import parsetex from songbook.plastex import parsetex
class Song: class Song:
#: Ordre de tri #: Ordre de tri
sort = [] sort = []
@ -19,10 +20,15 @@ class Song:
authwords = {"after": [], "ignore": [], "sep": []} authwords = {"after": [], "ignore": [], "sep": []}
def __init__(self, path, languages, titles, args): def __init__(self, path, languages, titles, args):
self.titles = titles self.titles = titles
self.normalized_titles = [locale.strxfrm(unprefixed_title(unidecode(unicode(title, "utf-8")), self.prefixes)) for title in titles] self.normalized_titles = [locale.strxfrm(
self.args = args unprefixed_title(unidecode(unicode(title, "utf-8")),
self.path = path self.prefixes
)
)
for title in titles]
self.args = args
self.path = path
self.languages = languages self.languages = languages
if "by" in self.args.keys(): if "by" in self.args.keys():
self.normalized_authors = [ self.normalized_authors = [
@ -59,6 +65,7 @@ class Song:
return 1 return 1
return 0 return 0
def unprefixed_title(title, prefixes): def unprefixed_title(title, prefixes):
"""Remove the first prefix of the list in the beginning of title (if any). """Remove the first prefix of the list in the beginning of title (if any).
""" """
@ -68,6 +75,7 @@ def unprefixed_title(title, prefixes):
return match.group(2) return match.group(2)
return title return title
class SongsList: class SongsList:
"""Manipulation et traitement de liste de chansons""" """Manipulation et traitement de liste de chansons"""
@ -78,7 +86,6 @@ class SongsList:
# Liste triée des chansons # Liste triée des chansons
self.songs = [] self.songs = []
def append(self, filename): def append(self, filename):
"""Ajout d'une chanson à la liste """Ajout d'une chanson à la liste
@ -113,7 +120,8 @@ class SongsList:
def latex(self): def latex(self):
"""Renvoie le code LaTeX nécessaire pour intégrer la liste de chansons. """Renvoie le code LaTeX nécessaire pour intégrer la liste de chansons.
""" """
result = [ '\\input{{{0}}}'.format(song.path.replace("\\","/").strip()) for song in self.songs] result = ['\\input{{{0}}}'.format(song.path.replace("\\", "/").strip())
for song in self.songs]
result.append('\\selectlanguage{%s}' % self._language) result.append('\\selectlanguage{%s}' % self._language)
return '\n'.join(result) return '\n'.join(result)

Loading…
Cancel
Save