Reference for all built-in template language functions

Here, we document all the built-in functions available in the calibre template language. Every function is implemented as a class in python and you can click the source links to see the source code, in case the documentation is insufficient. The functions are arranged in logical groups by type.

URL函数

encode_for_url

class calibre.utils.formatter_functions.BuiltinEncodeForURL[源代码]

encode_for_url(value, use_plus) -- 返回已编码的 value,用于 URL,并由 use_plus 指定。该值首先进行 URL 编码。接下来,如果 use_plus0,则空格将被 '+'``(加号)替换。如果为 ``1,则空格将被 %20 替换。

如果您不想对值进行编码,而是希望空格被替换,请使用 re() 函数,例如 re($series, ' ', '%20')

另请参阅函数 make_url()make_url_extended()query_string()

make_url

class calibre.utils.formatter_functions.BuiltinMakeUrl[源代码]

make_url(path, [query_name, query_value]+) -- 此函数是构建查询 URL 的最简单方法。它使用 path、要查询的网站和页面,以及用于构建查询的 query_namequery_value 对。 通常,query_value 必须进行 URL 编码。使用此函数时,它始终会进行编码,并且空格始终会替换为 '+' 符号。

必须至少提供一个 query_name, query_value 对。

示例:为作者“Niccolò Machiavelli”构建维基百科搜索 URL:

make_url('https://en.wikipedia.org/w/index.php', 'search', 'Niccolò Machiavelli')

返回

https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli

如果您正在编写自定义栏目书籍详情 URL 模板,请使用“$item_name”或“field('item_name')”获取被点击字段的值。 例如:如果点击了“Niccolò Machiavelli”,则可以使用以下代码构建 URL:

make_url('https://en.wikipedia.org/w/index.php', 'search', $item_name)

另请参阅函数 make_url_extended()query_string()encode_for_url()

make_url_extended

class calibre.utils.formatter_functions.BuiltinMakeUrlExtended[源代码]

make_url_extended(...) —— 此函数与 make_url() 类似,但 它能让你更好地控制 URL 的组成部分。URL 的组成部分包括:

scheme:://authority/path?query string

更多详情,请参阅维基百科上的 统一资源定位符

该函数有两种用法:

make_url_extended(scheme, authority, path, [query_name, query_value]+)

make_url_extended(scheme, authority, path, query_string)

此函数返回一个由 schemeauthoritypath 以及 query_string 或由查询参数对构成的查询字符串构成的 URL。 authority 可以为空,例如 用于``calibre`` 协议的 URL。 您必须提供一个 query_string 或至少一个 query_name, query_value 对。 如果您提供的 query_string 为空,则生成的 URL 将不包含查询字符串部分。

示例 1:为作者“Niccolò Machiavelli”构建维基百科搜索 URL:

make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', 'Niccolò Machiavelli')

返回

https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli

请参阅 query_string() 函数,其中有使用 make_url_extended()query_string 的示例。

如果您正在编写自定义栏目书籍详情 URL 模板,请使用 $item_name 或``field('item_name')`` 来获取被点击字段的值。 例如:如果点击了“Niccolò Machiavelli”,则可以使用以下代码构建 URL:

make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', $item_name')

另请参阅函数 make_url()query_string()encode_for_url()

query_string

class calibre.utils.formatter_functions.BuiltinQueryString[源代码]

query_string([query_name, query_value, how_to_encode]+)-- returns a URL query string constructed from the query_name, query_value, how_to_encode triads. A query string is a series of items where each item looks like query_name=query_value where query_value is URL-encoded as instructed. The query items are separated by '&' (ampersand) characters.

If how_to_encode is 0 then query_value is encoded and spaces are replaced with '+' (plus) signs. If how_to_encode is 1 then query_value is encoded with spaces replaced by %20. If how_to_encode is 2 then query_value is returned unchanged; no encoding is done and spaces are not replaced. If you want query_value not to be encoded but spaces to be replaced then use the re() function, as in re($series, ' ', '%20')

You use this function if you need specific control over how the parts of the query string are constructed. You could then use the resultingquery string in make_url_extended(), as in

make_url_extended(
       'https', 'your_host', 'your_path',
       query_string('encoded', 'Hendrik Bäßler', 0, 'unencoded', 'Hendrik Bäßler', 2))

giving you

https://your_host/your_path?encoded=Hendrik+B%C3%A4%C3%9Fler&unencoded=Hendrik Bäßler

You must have at least one query_name, query_value, how_to_encode triad, but can have as many as you wish.

The returned value is a URL query string with all the specified items, for example: name1=val1[&nameN=valN]*. Note that the '?' path / query string separator is not included in the returned result.

If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the unencoded value of the field that was clicked. You also have item_value_quoted where the value is already encoded with plus signs replacing spaces, and item_value_no_plus where the value is already encoded with %20 replacing spaces.

See also the functions make_url(), make_url_extended() and encode_for_url().

以英文显示文档,由于 FFML 错误: Newline unexpected in REF (:ref:`) on line 4 in "query_string"

to_hex

class calibre.utils.formatter_functions.BuiltinToHex[源代码]

to_hex(val) —— 返回编码为十六进制的字符串 val。 这在构建 calibre URL 时很有用。

urls_from_identifiers

class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers[源代码]

urls_from_identifiers(identifiers, sort_results) —— 给定一个以逗号分隔的 identifiers 列表,其中 identifier 是一对以冒号分隔的值(“id_name:id_value”),返回一个以逗号分隔的、由这些标识符生成的 HTML URL 列表。 如果 sort_results``0``(字符或数字),则列表不排序;否则,列表按标识符名称的字母顺序排序。URL 的生成方式与“书籍详情”中内置的标识符栏目相同。

​列表查找​​

identifier_in_list

class calibre.utils.formatter_functions.BuiltinIdentifierInList[源代码]

identifier_in_list(val, id_name [,found_val, not_found_val]) -- 将 val 视为以逗号分隔的标识符列表。 标识符的格式为“id_name:value”。 id_name 参数是要搜索的 id_name 文本,可以是 id_nameid_name:regexp。 如果有任何标识符与 id_name 匹配,则第一种情况匹配。 如果 id_name 与标识符匹配并且正则表达式与标识符的值匹配,则第二种情况匹配。 如果提供了“found_val”和“not_found_val”,则如果存在匹配则返回“found_val”,否则返回“not_found_val”。 如果未提供 found_valnot_found_val ,则如果存在匹配则返回 identifier:value 对,否则返回空字符串 ('')。

list_contains

class calibre.utils.formatter_functions.BuiltinInList[源代码]

list_contains(value, separation, [ pattern, found_val, ]* not_found_val) -- 将 value 解释为由 separator 分隔的项列表,并将 pattern 与列表中的每个项进行匹配。 如果 pattern 与某个项匹配,则返回 found_val,否则返回 not_found_valpatternfound_value 对可以根据需要重复多次,从而允许根据项的值返回不同的值。按顺序检查模式,并返回第一个匹配项。

别名:in_list()、list_contains()

list_item

class calibre.utils.formatter_functions.BuiltinListitem[源代码]

list_item(value, index, separation) —— 将 value 视为由 separator 分隔的项目列表,返回第 index 个项目。 列表的第一个项目编号为 0,最后一个项目的索引为 -1(例如:list_item(-1,separator))。 如果指定的索引超出列表范围,则返回空字符串。 separator 的含义与 count 函数中的相同,通常为逗号,但对于作者类的列表,分隔符是 &(与号)。

select

class calibre.utils.formatter_functions.BuiltinSelect[源代码]

select(value, key) —— 将 value 解释为以逗号分隔的项目列表,其中每个项目都具有 id:id_value 的形式(calibre identifier 格式)。 该函数查找 id 等于 key 的第一个对,并返回相应的 id_value。如果没有匹配的 id,则函数返回空字符串。

str_in_list

class calibre.utils.formatter_functions.BuiltinStrInList[源代码]

str_in_list(value, separation, [ string, found_val, ]+ not_found_val) ——将 value 解释为由 separator 分隔的项目列表,然后将 string 与列表中的每个值进行比较。 string 不是正则表达式。如果 string 等于任何项目(忽略大小写),则返回相应的 found_val。如果 string 包含 separators,则它也被视为列表,并检查每个子值。stringfound_value 对可以根据需要重复多次,允许根据字符串的值返回不同的值。如果没有字符串匹配,则返回 not_found_value。按顺序检查字符串。返回第一个匹配项。

从元数据中获取值

annotation_count

class calibre.utils.formatter_functions.BuiltinAnnotationCount[源代码]

annotation_count() ---返回属于前书籍的所有类型的标注总数。此功能仅用于GUI和内容服务器。

approximate_formats

class calibre.utils.formatter_functions.BuiltinApproximateFormats[源代码]

approximate_formats() -- 返回与书籍相关的格式列表,以逗号分隔。 由于该列表来自 calibre 的数据库而非文件系统,因此无法保证其正确性,尽管它可能是正确的。请注意,生成的格式名称始终为大写,就像 EPUB 格式一样。 approximate_formats() 函数比 formats_... 函数快得多。

此函数仅适用于 GUI。如果您想在保存到硬盘或发送到设备的模板中使用这些值,则必须创建自定义的“基于其它栏目创建栏目”,在该栏目的模板中使用该函数,并在保存/发送模板中使用该栏目的值。

author_sorts

class calibre.utils.formatter_functions.BuiltinAuthorSorts[源代码]

author_sorts(val_separator) -- returns a string containing a list of author's sort values for the authors of the book. The sort is the one in the author metadata information, which can be different from the author_sort in books. The returned list has the form author sort 1 val_separator author sort 2 etc. with no added spaces. The author sort values in this list are in the same order as the authors of the book. If you want spaces around val_separator then include them in the val_separator string.

以英文显示文档,由于 FFML 错误: Missing closing "`" for italics on line 2 in "author_sorts"

booksize

class calibre.utils.formatter_functions.BuiltinBooksize[源代码]

booksize() -- 返回 calibre size 字段的值。如果书籍没有格式,则返回 ''。

此函数仅在 GUI 中有效。如果您想在保存到硬盘或发送到设备的模板中使用此值,则必须创建自定义的“基于其它栏目创建栏目”,在该栏目的模板中使用该函数,并在保存/发送模板中使用该栏目的值。

connected_device_name

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[源代码]

connected_device_name(storage_location_key) -- 如果设备已连接,则返回设备名称,否则返回空字符串。 设备上的每个存储位置都有自己的设备名称。storage_location_key 名称为 'main''carda''cardb'。此函数仅在 GUI 中有效。

connected_device_uuid

class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID[源代码]

connected_device_uuid(storage_location_key) -- 如果设备已连接,则返回设备 uuid(唯一 ID),否则返回空字符串。 设备上的每个存储位置都有不同的 uuid。 storage_location_key 位置名称为``'main''carda'`` 和``'cardb'``。 此功能仅在 GUI 中有效。

current_library_name

class calibre.utils.formatter_functions.BuiltinCurrentLibraryName[源代码]

current_library_name()——返回当前 calibre 书库路径上的最新的名称。

current_library_path

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[源代码]

current_library_path()——返回当前 calibre书库的完整路径。

current_virtual_library_name

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[源代码]

current_virtual_library_name() --返回当前虚拟书库的名称(如果有),否则返回空字符串。 保留书库名称大小写。示例:

program: current_virtual_library_name()

此功能仅在图形用户界面(GUI)中有效。

field

class calibre.utils.formatter_functions.BuiltinField[源代码]

field(lookup_name) -- 返回查找名称为 lookup_name 的元数据字段的值。 可以使用 $ 前缀代替函数,例如 $tags

formats_modtimes

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[源代码]

formats_modtimes(date_format_string) —— 返回一个以逗号分隔的列表,其中包含以冒号分隔的项 FMT:DATE,这些项表示书籍格式的修改时间。 date_format_string 参数指定日期的格式化方式。有关详情,请参阅 format_date() 函数。您可以使用 select() 函数获取特定格式的修改时间。请注意,格式名称始终大写,就像 EPUB 一样。

formats_path_segments

class calibre.utils.formatter_functions.BuiltinFormatsPathSegments[源代码]

formats_path_segments(with_author, with_title, with_format, with_ext, sep) -- 返回 calibre 书库中书籍格式的路径部分,并以 sep 分隔。 参数 sep 通常为斜杠 (/')。一个用途是确保在“保存到硬盘”和“发送到设备”模板中生成的路径始终缩短。另一个用途是确保设备上的路径与 calibre 书库中的路径一致。

书籍路径由三个部分组成:作者、书名(括号中为 calibre 数据库 ID)以及格式(作者 - 书名)。由于文件名长度限制,Calibre 可以缩短这三个部分中的任何一个。您可以通过为该部分传递 1 来选择要包含的部分。如果您不需要某个部分,则为该段传递 0 或空字符串。例如,以下代码仅返回不带扩展名的格式名称:

formats_path_segments(0, 0, 1, 0, '/')

由于只有一个部分,因此分隔符将被忽略。

如果有多种格式(多个扩展名),则会随机选择其中一种扩展名。如果您关心使用的是哪种扩展名,则获取不带扩展名的路径,然后向其中添加所需的扩展名。

示例:假设 calibre 书库中有一本由 Joe Blogs 出版的 epub 格式书籍,书名是“Help”。路径应为

Joe Blogs/Help - (calibre_id)/Help - Joe Blogs.epub

以下显示了各个参数的返回值:

  • formats_path_segments(0, 0, 1, 0, '/') 返回 Help - Joe Blogs

  • formats_path_segments(0, 0, 1, 1, '/') 返回 Help - Joe Blogs.epub

  • formats_path_segments(1, 0, 1, 1, '/') 返回 Joe Blogs/Help - Joe Blogs.epub

  • formats_path_segments(1, 0, 1, 0, '/') 返回 Joe Blogs/Help - Joe Blogs

  • formats_path_segments(0, 1, 0, 0, '/') 返回 Help - (calibre_id)

formats_paths

class calibre.utils.formatter_functions.BuiltinFormatsPaths[源代码]

formats_paths([separator]) -- 返回一个以 separator 分隔的列表,其中包含以冒号分隔的项 FMT:PATH,给出书籍格式的完整路径。 separator 参数是可选的。如果未提供,则分隔符为 ', '``(逗号空格)。如果分隔符是逗号,则可以使用 ``select() 函数获取特定格式的路径。请注意,格式名称始终大写,就像EPUB 这样。

formats_sizes

class calibre.utils.formatter_functions.BuiltinFormatsSizes[源代码]

formats_sizes() -- 返回以逗号分隔的 FMT:SIZE 项列表,这些项以冒号分隔,并以字节为单位给出书籍格式的文件大小。 您可以使用 select() 函数获取特定格式的文件大小。请注意,格式名称始终大写,就像 EPUB 一样。

has_cover

class calibre.utils.formatter_functions.BuiltinHasCover[源代码]

has_cover() --如果书有封面,则返回“Yes”,否则返回空字符串。

is_marked

class calibre.utils.formatter_functions.BuiltinIsMarked[源代码]

is_marked() --检查书籍在calibre中是否“标记”。如果是,则返回标记的值,“true”(小写)或逗号分隔的标记名称列表。如果书籍未标记,则返回 ``''``(空字符串)。此函数仅在图形界面有效。

language_codes

class calibre.utils.formatter_functions.BuiltinLanguageCodes[源代码]

language_codes(lang_strings) —— 返回传入 lang_strings 的语言名称的 语言代码。 字符串必须采用当前语言环境的语言。lang_strings 是一个逗号分隔的列表。

language_strings

class calibre.utils.formatter_functions.BuiltinLanguageStrings[源代码]

language_strings(value, localize) -- 返回传入 value 的语言代码对应的语言名称(请参阅此处了解名称和代码)。 示例:{languages:language_strings()}。 如果 localize 为零,则返回英文字符串。如果 localize 不为零,则返回当前语言环境对应的语言字符串。lang_codes 是一个逗号分隔的列表。

ondevice

class calibre.utils.formatter_functions.BuiltinOndevice[源代码]

ondevice() -- 如果设置了 ondevice,则返回字符串 'Yes',否则返回空字符串。 此函数仅在 GUI 中有效。如果您想在保存到硬盘或发送到设备的模板中使用此值,则必须自定义一个“基于其它栏目创建栏目”,在该栏目的模板中使用该函数,并在保存/发送模板中使用该栏目的值。

raw_field

class calibre.utils.formatter_functions.BuiltinRawField[源代码]

raw_field(lookup_name [,optional_default]) —— 返回由 lookup_name 命名的元数据字段,不应用任何格式。 如果字段值未定义(“None”),则计算并返回可选的第二个参数 optional_default。可以使用 $$ 前缀代替函数,例如 $$pubdate

raw_list

class calibre.utils.formatter_functions.BuiltinRawList[源代码]

raw_list(lookup_name, separation) —— 返回由 lookup_name 命名的元数据列表,不应用任何格式或排序,其中的项目由 separator 分隔。

series_sort

class calibre.utils.formatter_functions.BuiltinSeriesSort[源代码]

series_sort() -- 返回丛书排序值

user_categories

class calibre.utils.formatter_functions.BuiltinUserCategories[源代码]

user_categories() -- 返回由逗号分隔的包含这本书'自定义属性'的列表。 这个函数只在图形界面中工作。如果要在保存到硬盘或发送到设备模板中使用这些值,则需自定义一个“基于其它栏目创建栏目”,使用该栏目的模板中的函数,并在保存/发送模板中使用该栏目的值

virtual_libraries

class calibre.utils.formatter_functions.BuiltinVirtualLibraries[源代码]

virtual_libraries() -- 返回包含这本书的以逗号分隔的虚拟书库列表。 此功能仅在GUI中有效。如果要在保存到硬盘或发送到设备模板中使用这些值,则必须自定义“基于其它栏目创建栏目”,使用该栏目模板中的函数,并在保存/发送模板中使用该栏目的值。

关系型

cmp

class calibre.utils.formatter_functions.BuiltinCmp[源代码]

cmp(value, y, lt, eq, gt) -- 将 valuey 转换为数字后进行比较。 如果 value <# y 则返回 lt,如果 value ==# y 则返回 eq,否则返回 gt。 此函数通常可以用数字比较运算符之一替换(例如 ==#<#># 等)。

first_matching_cmp

class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[源代码]

first_matching_cmp(val, [ cmp, result, ]* else_result) -- 按顺序比较 val < cmp,返回第一个成功比较的 result。 如果所有比较均失败,则返回 else_result

示例:

i = 10;
first_matching_cmp(i,5,"small",10,"middle",15,"large","giant")

返回 "large"。同一示例,如果第一个值为 16,则返回 "giant"

strcmp

class calibre.utils.formatter_functions.BuiltinStrcmp[源代码]

strcmp(x, y, lt, eq, gt) -- 作为字符串比较 x 和 y,不区分大小写。当 x < y 时返回 lt,x = y 时返回 eq,否则返回 gt。此函数通常可以用词法比较运算符(==>< 等)替换。

strcmpcase

class calibre.utils.formatter_functions.BuiltinStrcmpcase[源代码]

strcmpcase(x, y, lt, eq, gt) -- 对 xy 进行区分大小写的词法比较。 如果 x < y 返回 lt,如果 x == y 返回 eq,否则返回 gt

注意:这不是 calibre 使用的默认行为,例如,在词法比较运算符(==>< 等)中。此函数可能导致意外结果,建议尽可能使用 strcmp()

其他

arguments

class calibre.utils.formatter_functions.BuiltinArguments[源代码]

arguments(id[=expression] [, id[=expression]]*) —— 在存档模板中用于检索调用中传递的参数。 它使用提供的名称 id 声明并初始化局部变量,使其成为有效的参数。这些变量是位置相关的;它们在调用的相同位置获取给定参数的值。如果调用中未提供相应的参数,则 arguments() 会将提供的默认值赋给该变量。如果没有默认值,则将变量设置为空字符串。

assign

class calibre.utils.formatter_functions.BuiltinAssign[源代码]

assign(id, value) —— 将 value 赋值给 id,然后返回 valueid 必须是标识符,而不是表达式。大多数情况下,您可以使用 = 运算符代替此函数。

globals

class calibre.utils.formatter_functions.BuiltinGlobals[源代码]

globals(id[=expression] [, id[=expression]]*) —— 检索可传递到格式化程序的“全局变量”。 名称 id 是全局变量的名称。它使用传入的全局变量的名称(“id”参数)声明并初始化局部变量。如果全局变量中未提供相应的变量,则它会将提供的默认值赋给该变量。如果没有默认值,则将变量设置为空字符串。

is_dark_mode

class calibre.utils.formatter_functions.BuiltinIsDarkMode[源代码]

is_dark_mode() -- 若calibre运行于夜间模式,返回``'1',否则返回''``(空字符串)。 高级颜色和图标规则中,可用此函数按模式选择不同的颜色或图标。示例:

if is_dark_mode() then 'dark.png' else 'light.png' fi

print

class calibre.utils.formatter_functions.BuiltinPrint[源代码]

print(a [, b]*) —— 将参数输出到标准输出(即打印出来)。 除非你是从命令行使用 calibre-debug -g 启动 calibre,否则输出内容将会被“丢进黑洞”(即看不到)。 ``print``函数始终返回它的第一个参数。

set_globals

class calibre.utils.formatter_functions.BuiltinSetGlobals[源代码]

set_globals(id[=expression] [, id[=expression]]*) —— 设置可以传递到格式化程序的 全局变量。 全局变量被赋予传入的 id 的名称。除非提供了表达式,否则使用 id 的值。

列表操作

list_count

class calibre.utils.formatter_functions.BuiltinCount[源代码]

list_count(value, separator) -- 将值解析为由 separator 分隔的项目列表,并返回列表中的项目数量。 大多数列表使用逗号作为分隔符,但 authors 使用与号 (&)。

示例:{tags:list_count(,)}{authors:list_count(&)}

别名:count()list_count()

list_count_field

class calibre.utils.formatter_functions.BuiltinFieldListCount[源代码]

list_count_field(lookup_name)-- 返回查找名称为 lookup_name 的字段中的项目数量。 该字段必须是多值字段,例如 authorstags,否则函数会抛出错误。 此函数比 list_count() 快得多,因为它直接操作 calibre 数据,而无需先将其转换为字符串。 示​​例:list_count_field('tags')

list_count_matching

class calibre.utils.formatter_functions.BuiltinListCountMatching[源代码]

list_count_matching(value, pattern, separation) ——将 value 解释为由 separator 分隔的项目列表,返回列表中与正则表达式 pattern 匹配的项目数。 别名:list_count_matching()count_matching()

list_difference

class calibre.utils.formatter_functions.BuiltinListDifference[源代码]

list_difference(list1, list2, separation) —— 返回一个列表,该列表通过不区分大小写的比较从 list1 中删除在 list2``中找到的任何项目而形成。 ``list1list2 中的项目之间用 separator 分隔,返回列表中的项目之间也用 separator 分隔。

list_equals

class calibre.utils.formatter_functions.BuiltinListEquals[源代码]

list_equals(list1, sep1, list2, sep2, yes_val, no_val) - 如果 list1list2 包含相同的项,则返回 yes_val,否则返回 no_val。 通过使用适当的分隔符(“sep1”或“sep2”)拆分每个列表来确定项。列表中项的顺序无关紧要。比较时不区分大小写。

list_intersection

class calibre.utils.formatter_functions.BuiltinListIntersection[源代码]

list_intersection(list1, list2, separation) —— 返回一个列表,该列表通过从 list1 中删除任何在 list2``中找不到的项目而形成,列表对比时不区分大小写。``list1list2 中的项目之间用 separator 分隔,返回列表中的项目之间也用 separator 分隔。

list_join

class calibre.utils.formatter_functions.BuiltinListJoin[源代码]

list_join(with_separator, list1, separation1 [, list2, separation2]*) -- 返回一个列表,该列表由源列表(例如 list1)中的项目组成, 并在结果列表中的项目之间使用 with_separator 连接。每个源 list[123...] 中的项目由关联的 separator[123...] 分隔。 列表可以包含零值。它可以是像 publisher 这样的单值字段,实际上就是一个包含一个项目的列表。使用不区分大小写的比较来删除重复项。项目按其在源列表中出现的顺序返回。如果列表中的项目仅在字母大小写上不同,则使用最后一个字母。所有分隔符都可以包含多个字符。

示例:

program:
list_join('#@#', $authors, '&', $tags, ',')

您可以对之前调用 list_join 的结果使用 list_join,如下所示:

program:
a = list_join('#@#', $authors, '&', $tags, ',');
b = list_join('#@#', a, '#@#', $#genre, ',', $#people, '&', 'some value', ',')

您可以使用表达式生成列表。例如,假设您需要“authors”和“#genre”的条目,但类型更改为“Genre:”后跟类型首字母,即类型“Fiction”变为“Genre: F”。以下命令将执行此操作:

program:
    list_join('#@#', $authors, '&', list_re($#genre, ',', '^(.).*$', 'Genre: \1'),  ',')

list_re

class calibre.utils.formatter_functions.BuiltinListRe[源代码]

list_re(src_list,separator, include_re, opt_replace) -- 首先使用``separator`` 字符将``src_list`` 分隔成项目来构造一个列表。 对于列表中的每个项目,检查它是否与“include_re”匹配。 如果是,则将其添加到要返回的列表中。 如果“opt_replace”不是空字符串,则在将项目添加到返回的列表之前应用替换。

list_re_group

class calibre.utils.formatter_functions.BuiltinListReGroup[源代码]

list_re_group(src_list, separation, include_re, search_re [,template_for_group]*) -- 与 list_re 类似,但替换不是可选的。 进行替换时,它使用 re_group(item, search_re, template ...)

list_remove_duplicates

class calibre.utils.formatter_functions.BuiltinListRemoveDuplicates[源代码]

list_remove_duplicates(list, separation) —— 返回一个通过移除 list 中的重复项而生成的列表。 如果项仅大小写不同,则返回最后一个。list 中的项用``separator`` 分隔。返回列表中的项之间也以 separator 分隔。

list_sort

class calibre.utils.formatter_functions.BuiltinListSort[源代码]

list_sort(value, direction, separation) -- 返回使用不区分大小写的字典排序方法排序的 value。 如果 direction 为零(数字或字符),则 value 按升序排列,否则按降序排列。列表项由 separator 分隔,返回列表中的项也由 separator 分隔。

list_split

class calibre.utils.formatter_functions.BuiltinListSplit[源代码]

list_split(list_val, sep, id_prefix) -- 使用 seplist_val 拆分为单独的值,然后将这些值赋给名为 id_prefix_N 的局部变量,其中 N 是值在列表中的位置。第一个元素的位置为 0(零)。该函数返回列表中的最后一个元素。

示例:

list_split('one:two:foo', ':', 'var')

等同于:

var_0 = 'one'
var_1 = 'two'
var_2 = 'foo'

list_union

class calibre.utils.formatter_functions.BuiltinListUnion[源代码]

list_union(list1, list2, separator) -- 返回通过合并“list 1”和“list 2”中的项而创建的列表,使用不区分大小写的比较删除重复的项。如果项目的大小写不同,则使用“列表1”中的项目。“list 1”和“list 2”中的项由“分隔符”分隔,返回列表中的项也是如此。别名:merge_lists(), list_union()

range

class calibre.utils.formatter_functions.BuiltinRange[源代码]

range(start, stop, step, limit) —— 返回一个数字列表,该列表是通过在参数 startstopstep 所指定的范围内循环生成的,列表最大长度由``limit``决定。 生成的第一个值是 start。之后的每个值为``next_v = current_v + step``。若 step 为正数,则循环条件为``next_v < stop`` ;若为负数,则条件为``next_v > stop`` 。如果``start`` 不满足初始条件(如``step`` 为正但 start >= stop),则返回空列表。 limit 是列表长度上限,默认值为 1000。参数 startsteplimit 为可选项: 调用``range()`` 同时带有一个指定参数 “stop”或两个指定参数“start”、“stop”或三个指定参数“start”、“stop”、“step”或四个指定参数“start”、“stop”、“step”和“limit”。 示例:

range(5) -> '0, 1, 2, 3, 4'
range(0, 5) -> '0, 1, 2, 3, 4'
range(-1, 5) -> '-1, 0, 1, 2, 3, 4'
range(1, 5) -> '1, 2, 3, 4'
range(1, 5, 2) -> '1, 3'
range(1, 5, 2, 5) -> '1, 3'
range(1, 5, 2, 1) -> error(limit exceeded)

subitems

class calibre.utils.formatter_functions.BuiltinSubitems[源代码]

subitems(value, start_index, end_index) -- 此函数用于拆分类似标签的层级显示项目列表,例如类型。 它将 value 解释为以逗号分隔的类似标签的项目列表,其中每个项目都是一个以句点分隔的列表。它返回一个新列表,该列表由每个项目提取从 start_indexend_index 的元素,然后将结果合并在一起而形成。 重复项将被删除。以句点分隔的列表中的第一个子项目的索引为零。如果索引为负数,则从列表末尾开始计算。 作为特例,当 end_index 为零时,系统会假定该列表的长度。

示例:

  • 假设 #genre 栏目包含“A.B.C”:

    • {#genre:subitems(0,1)} 返回“A”

    • {#genre:subitems(0,2)} 返回“A.B”

    • {#genre:subitems(1,0)} 返回“B.C”

  • 假设 #genre 栏目包含“A.B.C, D.E”:

    • {#genre:subitems(0,1)} 返回“A, D”

    • {#genre:subitems(0,2)} 返回“A.B, D.E”

sublist

class calibre.utils.formatter_functions.BuiltinSublist[源代码]

sublist(value, start_index, end_index, separation) -- 将 value 解释为由 separator 分隔的项列表,并返回一个由 start_indexend_index 的项组成的新列表。 第一个项为零。如果索引为负数,则从列表末尾开始计算。 特殊情况,如果 end_index 为零,则假定其为列表的长度。

以下示例假设 tags 列(以逗号分隔)包含“A, B, C”:

  • {tags:sublist(0,1,\,)} 返回“A”

  • {tags:sublist(-1,0,\,)} 返回“C”

  • {tags:sublist(0,-1,\,)} 返回“A, B”

大小写转换

capitalize

class calibre.utils.formatter_functions.BuiltinCapitalize[源代码]

capitalize(value)——返回首字母大写、其余字母小写的``value``。

lowercase

class calibre.utils.formatter_functions.BuiltinLowercase[源代码]

lowercase(value)——以小写形式返回``value``。

titlecase

class calibre.utils.formatter_functions.BuiltinTitlecase[源代码]

titlecase(value)——返回将 value 转换为标题大小写的结果。

uppercase

class calibre.utils.formatter_functions.BuiltinUppercase[源代码]

uppercase(value)——以大写形式返回``value``。

字符串操作

character

class calibre.utils.formatter_functions.BuiltinCharacter[源代码]

character(character_name) —— 返回由 character_name 命名的字符。 例如,character('newline') 返回换行符('\n')。支持的字符名称包括 newlinereturntabbackslash。此函数用于将这些字符放入模板的输出中。

check_yes_no

class calibre.utils.formatter_functions.BuiltinCheckYesNo[源代码]

check_yes_no(field_name, is_undefined, is_false, is_true) -- 检查查找名称为 field_name 的“yes/no”字段的值是否为参数指定的值之一,如果匹配则返回 'Yes',否则返回空字符串。将参数 is_undefinedis_falseis_true 设置为 1(数字)以检查该条件,否则将其设置为 0。

示例:如果 yes/no 字段 #bool 为 True 或未定义(既不是 True 也不是 False),check_yes_no("#bool", 1, 0, 1) 则返回 'Yes'

可以将多个 is_undefinedis_falseis_true 设置为 1。

contains

class calibre.utils.formatter_functions.BuiltinContains[源代码]

contains(value, pattern, text_if_match, text_if_not_match) —— 检查值是否与正则表达式 pattern 匹配。如果匹配,则返回 text_if_match,否则返回 text_if_not_match

field_exists

class calibre.utils.formatter_functions.BuiltinFieldExists[源代码]

field_exists(lookup_name)——检查是否存在具有查找名称``lookup_name``的字段(栏目),如果存在则返回``'1'``,如果不存在则返回空字符串。

ifempty

class calibre.utils.formatter_functions.BuiltinIfempty[源代码]

ifempty(value, text_if_empty)——如果``value``不为空则返回该``value``,否则返回``text_if_empty``。

re

class calibre.utils.formatter_functions.BuiltinRe[源代码]

re(value, pattern, replacement) —— 对 value 应用正则表达式后返回结果。 value 中所有匹配 pattern 的部分都会被 replacement 替换。模板语言使用不区分大小写的 Python 正则表达式

re_group

class calibre.utils.formatter_functions.BuiltinReGroup[源代码]

re_group(value, pattern [, template_for_group]*) -- 将正则表达式 pattern 应用于 value,并将每个匹配的部分替换为对应模板生成的值,最终返回处理后的字符串。在 模板程序模式 中,与 template 和``eval`` 函数一样,使用 [[ 表示 {,使用 ]] 表示 }

以下示例查找包含多个单词的丛书,并将第一个单词大写:

program: re_group(field('series'), "(\S* )(.*)", "{$:uppercase()}", "{$}")'}

shorten

class calibre.utils.formatter_functions.BuiltinShorten[源代码]

shorten(value, left_chars, middle_text, right_chars) -- 返回 value 的缩短版本,包含 value 开头的 left_chars 个字符,接着是 middle_text,然后是 value 结尾的 right_chars 个字符。left_charsright_chars 必须是非负整数。

示例:假设您希望显示长度最多为 15 个字符的标题。一个可执行此操作的模板是 {title:shorten(9,-,5)}。对于书名是《Ancient English Laws in the Times of Ivanhoe》的书,结果将是《Ancient E-anhoe》:标题的前 9 个字符,一个 -,然后是最后 5 个字符。如果值的长度小于“左侧字符”+“右侧字符”+“中间文本”的长度,则该值将保持不变。例如,标题“The Dome”将不会更改。

strcat

class calibre.utils.formatter_functions.BuiltinStrcat[源代码]

strcat(a [, b]*) -- 返回由所有参数连接而成的字符串。 可以接受任意数量的参数。大多数情况下,您可以使用 & 运算符代替此函数。

strcat_max

class calibre.utils.formatter_functions.BuiltinStrcatMax[源代码]

strcat_max(max, string1 [, prefix2, string2]*) -- 返回通过连接参数形成的字符串。 返回值被初始化为“string1”。 只要生成的字符串长度小于“max”,由“prefix, string”对组成的字符串就会添加到值的末尾。 前缀可以为空。 即使“string1”比“max”长,也会返回“string1”。 您可以根据需要传递任意数量的“前缀、字符串”对。

strlen

class calibre.utils.formatter_functions.BuiltinStrlen[源代码]

strlen(value)——返回字符串``value``的长度。

substr

class calibre.utils.formatter_functions.BuiltinSubstr[源代码]

substr(value, start, end) —— 返回 value 中从 startend 的字符。value 中的第一个字符是第零个字符。如果 end 为负数,则表示从右边数多少个字符。如果 end 为零,则表示最后一个字符。例如,substr('12345', 1, 0) 返回 '2345',而 substr('12345', 1, -1) 返回 '234'

swap_around_articles

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[源代码]

swap_around_articles(value, separation) -- 返回将冠词移至末尾并用分号分隔的 valuevalue 可以是列表,在这种情况下,列表中的每个项目都会被处理。如果 value 是列表,则必须提供 separator。如果没有提供 separator 或分隔符为空字符串,则 value 将被视为单个值,而不是列表。 articles 是 calibre 用于生成 title_sort 时使用的冠词。

swap_around_comma

class calibre.utils.formatter_functions.BuiltinSwapAroundComma[源代码]

swap_around_comma(value) —— 如果 value 的格式为``B, A`` ,则返回 A B。 此函数最常用于将 LN、FN (“姓, 名”,Last Name, First Name)格式的名字转换为 FN LN (“名 姓”First Name Last Name)格式。 如果 value 中没有逗号,则该函数将返回未更改的值。

test

class calibre.utils.formatter_functions.BuiltinTest[源代码]

test(value, text_if_not_empty, text_if_empty)——如果值不为空,则返回``text_if_not_empty``,否则返回``text_if_empty``。

transliterate

class calibre.utils.formatter_functions.BuiltinTransliterate[源代码]

transliterate(value) —— 返回一个由近似于 value 中的单词的发音组成的拉丁字母字符串。 例如,如果 valueФёдор Миха́йлович Достоевский,则此函数返回 Fiodor Mikhailovich Dostoievskii

布尔值

and

class calibre.utils.formatter_functions.BuiltinAnd[源代码]

and(value [, value]*) -- 如果所有值都不为空,则返回字符串 '1',否则返回空字符串。 您可以拥有任意数量的值。在大多数情况下,您可以使用 && 运算符代替此函数。 不将 and() 替换为 && 的一个原因是,短路运算可能会因副作用而改变结果。 例如,and(a='',b=5) 始终会执行两个赋值操作,而 && 运算符不会执行第二个赋值操作。

not

class calibre.utils.formatter_functions.BuiltinNot[源代码]

not(value) —— 如果值为空,则返回字符串 '1',否则返回空字符串。 该函数通常可以用一元逻辑非运算符()替换。

or

class calibre.utils.formatter_functions.BuiltinOr[源代码]

or(value [, value]*) -- 如果任何值不为空,则返回字符串 '1',否则返回空字符串。 您可以拥有任意多个值。 该函数通常可以用“||”运算符替换。 无法更换的一个原因是短路会因副作用而改变结果。

数据库函数

book_count

class calibre.utils.formatter_functions.BuiltinBookCount[源代码]

book_count(query, use_vl) -- 返回通过搜索 query 找到的书籍数量。 如果 use_vl0``(零),则虚拟书库将被忽略。 此函数及其配套函数 ``book_values() 在模板搜索中特别有用,支持组合多本书信息的搜索,例如查找只有一本书的丛书。除非将 allow_template_database_functions_in_composites 设置为 True,否则它不能用于复合栏目。它只能在 GUI 中使用。

例如,以下模板搜索使用此函数及其配套函数查找所有只有一本书的丛书:

  • 定义一个名为 series_only_one_book 的存档模板(使用 Preferences → Advanced → Template functions),名称为 ``series_only_one_book``(名称任意)。模板如下:

    program:
    vals = globals(vals='');
    if !vals then
    all_series = book_values('series', 'series:true', ',', 0);
    for series in all_series:
    if book_count('series:="' & series & '"', 0) == 1 then
    vals = list_join(',', vals, ',', series, ',')
    fi
    rof;
    set_globals(vals)
    fi;
    str_in_list(vals, ',', $series, 1, '')
    

    模板首次运行时(检查第一本书时),它会将数据库查找的结果存储在名为“vals”的“全局”模板变量中。这些结果可用于检查后续书籍,而无需重复查找。

  • 在模板搜索中使用存档模板:

template:"program: series_only_one_book()#@#:n:1"

使用存档模板(而不是将模板直接放入搜索中)可以消除搜索表达式中需要转义引号而导致的问题。

此功能只能在 GUI 和内容服务器中使用。

book_values

class calibre.utils.formatter_functions.BuiltinBookValues[源代码]

book_values(column, query, sep, use_vl) - 返回通过搜索 query 找到的书籍中 column 栏目(查找名称)中包含的唯一值列表,这些值以 sep 分隔。 如果 use_vl0``(零),则忽略虚拟书库。此函数及其配套函数 ``book_count() 在模板搜索中特别有用,支持结合多本书信息的搜索,例如查找只有一本书的丛书。除非将调整 allow_template_database_functions_in_composites 设置为 True,否则它不能在复合栏目中使用。此函数只能在 GUI 和内容服务器中使用。

extra_file_modtime

class calibre.utils.formatter_functions.BuiltinExtraFileModtime[源代码]

extra_file_modtime(file_name, format_string) —— 返回书籍 data/ 文件夹中附加文件 file_name 的修改时间(如果存在),不存在时返回 -1。modtime 根据 format_string 格式化(详情请参阅 format_date())。 如果 format_string 为空字符串,则返回 modtime 为自纪元以来的浮点秒数。 另请参阅函数 has_extra_files()extra_file_names()extra_file_size()。 纪元取决于操作系统。此函数只能在 GUI 和内容服务器中使用。

extra_file_names

class calibre.utils.formatter_functions.BuiltinExtraFileNames[源代码]

extra_file_names(sep [, pattern]) —— 返回书籍 data/ 文件夹中以 sep 分隔的附加文件列表。 如果提供了可选参数 pattern``(一个正则表达式),则列表将被过滤为与 ``pattern 匹配的文件。匹配时不区分大小写。 另请参阅函数 has_extra_files()extra_file_modtime()extra_file_size()。 此函数只能在 GUI 和内容服务器中使用。

extra_file_size

class calibre.utils.formatter_functions.BuiltinExtraFileSize[源代码]

extra_file_size(file_name) —— 如果存在,则返回书籍 data/ 文件夹中附加文件 file_name 的大小(以字节为单位),否则返回 -1。 另请参阅函数 has_extra_files()extra_file_names()extra_file_modtime()。 此函数只能在 GUI 和内容服务器中使用。

get_note

class calibre.utils.formatter_functions.BuiltinGetNote[源代码]

get_note(field_name, field_value, plain_text) -- fetch the note for field field_name with value field_value. If plain_text is empty, return the note's HTML including images. If plain_text is 1 (or '1'), return the note's plain text. If the note doesn't exist, return the empty string in both cases. Example:

  • Return the HTML of the note attached to the tag Fiction:

    program:
        get_note('tags', 'Fiction', '')
    
  • Return the plain text of the note attached to the author Isaac Asimov:

    program:
        get_note('authors', 'Isaac Asimov', 1)
    

This function works only in the GUI and the content server.

以英文显示文档,由于 FFML 错误: Missing closing "``" for CODE_TEXT on line 2 in "get_note"

has_extra_files

class calibre.utils.formatter_functions.BuiltinHasExtraFiles[源代码]

has_extra_files([pattern]) —— 返回附加文件的数量,否则返回 ''(空字符串)。 如果提供了可选参数 pattern``(正则表达式),则在统计文件数之前,会过滤列表中与 ``pattern 匹配的文件。匹配时不区分大小写。 另请参阅函数 extra_file_names()extra_file_size()extra_file_modtime()。 此函数只能在 GUI 和内容服务器中使用。

has_note

class calibre.utils.formatter_functions.BuiltinHasNote[源代码]

has_note(field_name, field_value) 检查字段是否带有备注。 此函数有两种变体:

  • 如果 field_value 不为 ''``(空字符串),则当字段 ``field_name 中的值 field_value 带有备注时,返回 '1',否则返回 ''。 示例:has_note('tags', 'Fiction') 当标签 fiction 带有附加备注时,返回 '1',否则返回 ''

  • 如果 field_value'',则返回 field_name 中带有备注的值列表。如果字段中没有任何项带有备注,则返回 ''。此变体可用于在字段中任何值带有备注(而非特定值)时显示栏目图标。 示例:has_note('authors', '') 返回带有备注的作者列表,或者,如果所有作者都没有备注,则返回 ''

您可以通过比较此函数返回值的列表长度与 field_name 中值的列表长度来测试 field_name 中的所有值是否都带有备注。 示例:

list_count(has_note('authors', ''), '&') ==# list_count_field('authors')

此函数仅适用于 GUI 和内容服务器。

日期函数

date_arithmetic

class calibre.utils.formatter_functions.BuiltinDateArithmetic[源代码]

date_arithmetic(value, calc_spec, fmt) -- 使用 calc_spec 根据 value 计算新的日期。 返回的新日期根据可选参数``fmt``格式化:如果未提供,则结果将采用 ISO 格式。 calc_spec 是一个由 vW (valueWhat) 对组成的字符串,其中 v 为可能为负的数,W 为以下字母之一:

  • s:将 date 加上 v

  • m:将 date 加上 v 分钟

  • h:将 date 加上 v 小时

  • d:将 date 加上 v

  • w:将 date 加上 v

  • y:将 date 加上 v 年,一年为 365 天。

示例:“'1s3d-1m'” 将在“date”中添加 1 秒、3 天并减去 1 分钟。

days_between

class calibre.utils.formatter_functions.BuiltinDaysBetween[源代码]

days_between(date1, date2) -- 返回 date1date2 之间的天数。 如果 date1 大于 date2,则该数字为正数,否则为负数。如果 date1date2 不是日期,则函数返回空字符串。

today

class calibre.utils.formatter_functions.BuiltinToday[源代码]

today() -- 返回今天(现在)的 日期+时间 字符串。 此值设计用于 format_datedays_between,但可以像其他字符串一样进行操作。日期采用 ISO 日期/时间格式。

格式化值

finish_formatting

class calibre.utils.formatter_functions.BuiltinFinishFormatting[源代码]

finish_formatting(value, format, prefix, suffix) -- 将 formatprefixsuffix 应用于 value,其方式与 {series_index:05.2f| - |- } 之类的模板中相同。 此函数用于简化将复杂的单函数或模板程序模式模板转换为 GPM (通用程序模式)模板的过程。 例如,以下程序将生成与上述模板相同的输出:

program: finish_formatting(field("series_index"), "05.2f", " - ", " - ")

另一个示例:对于模板:

{series:re(([^\s])[^\s]+(\s|$),\1)}{series_index:0>2s| - | - {title}

使用:

program:
strcat(
re(field('series'), '([^\s])[^\s]+(\s|$)', '\1'),
finish_formatting(field('series_index'), '0>2s', ' - ', ' - '),
field('title')
)

format_date

class calibre.utils.formatter_functions.BuiltinFormatDate[源代码]

format_date(value, format_string) -- 使用 format_string 格式化 value``(必须是日期字符串),并返回字符串。 日期最好采用 ISO 格式,因为使用其他日期格式通常会导致错误,因为无法明确确定实际的日期值。请注意,``format_date_field() 函数速度更快,也更可靠。

格式代码如下:

  • d : 以数字形式表示的日期,不带前导零(1 到 31)

  • dd : 以数字形式表示的日期,带前导零(01 到 31)

  • ddd : 本地化日期名称的缩写(例如:"周一" 到 "周日")

  • dddd : 本地化日期名称的长整型(例如:"星期一" 到 "星期日")

  • M : 以数字形式表示的月份,不带前导零(1 到 12)

  • MM : 以数字形式表示的月份,带前导零(01 到 12)

  • MMM : 本地化月份名称的缩写(例如:"1月" 到 "12月")

  • MMMM : 本地化月份名称的长整型(例如: “一月”至“十二月”)

  • yy :两位数年份(00 至 99)

  • yyyy :四位数年份。

  • ``h :小时数不带前导 0(0 到 11 或 0 到 23,取决于上午/下午) [*]``hh :小时数带前导 0(00 到 11 或 00 到 23,取决于上午/下午)

  • ``m :分钟数不带前导 0(0 到 59) [*]``mm :分钟数带前导 0(00 到 59)

  • ``s :秒数不带前导 0(0 到 59) [*]``ss :秒数带前导 0(00 到 59)

  • ``ap :使用 12 小时制而非 24 小时制,其中 'ap' 替换为表示上午或下午的小写本地化字符串 [*]``AP :使用 12 小时制而不是 24 小时制,将“AP”替换为表示上午 (AM) 或下午 (PM) 的大写本地化字符串。

  • aP : 使用 12 小时制而非 24 小时制,将“aP”替换为表示上午 (AM) 或下午 (PM) 的本地化字符串。

  • Ap : 使用 12 小时制而非 24 小时制,将“Ap”替换为表示上午 (AM) 或下午 (PM) 的本地化字符串。

  • iso : 包含时间和时区的日期。必须是唯一存在的格式。

  • to_number : 将日期和时间转换为浮点数(“时间戳”)。

  • from_number : 将浮点数(“时间戳”)转换为 ISO 格式的日期。如果您想要不同的日期格式,请在 from_number 和冒号(“:”)后添加所需的格式字符串。示例:

    format_date(val, 'from_number:MMM dd yyyy')
    

如果您要格式化的日期包含本地化的月份名称,则可能会出现意外结果,如果您将日期格式更改为包含“MMMM”,则可能会发生这种情况。使用“format_date_field()”可以避免此问题。

format_date_field

class calibre.utils.formatter_functions.BuiltinFormatDateField[源代码]

format_date_field(field_name, format_string) -- 格式化字段 field_name 中的值,该字段必须是日期字段的查找名称,可以是标准字段或自定义字段。 有关格式化代码,请参阅 format_date()。 此函数比 format_date() 快得多,应该在格式化字段(栏目)中的值时使用。它也更可靠,因为它直接作用于基础日期。它不能用于计算日期或字符串变量中的日期。 示例:

format_date_field('pubdate', 'yyyy.MM.dd')
format_date_field('#date_read', 'MMM dd, yyyy')

format_duration

class calibre.utils.formatter_functions.BuiltinFormatDuration[源代码]

format_duration(value, template, [largest_unit]) -- 将以秒为单位的数字 value 格式化为包含周、天、小时、分钟和秒的人类可读字符串。如果值为浮点数,则四舍五入为最接近的整数。 你可以使用模板 template 来定义格式,模板由一组用方括号 [ ] 括起来的值选择符组成,支持以下选择符:

  • [w]: 周

  • [d]: 天

  • [h]: 小时

  • [m]: 分钟

  • [s]: 秒

你可以在选择符之间插入任意文本。

以下示例使用的时长为 2 天(172,800 秒)加 1 小时(3,600 秒)加 20 秒,总计 176,420 秒。

  • format_duration(176420, '[d][h][m][s]') 将返回值 2d 1h 0m 20s

  • format_duration(176420, '[h][m][s]') 将返回值 49h 0m 20s

  • format_duration(176420, '您的阅读时间为 [d][h][m][s]') 将返回值 您的阅读时间为 49h 0m 20s

  • format_duration(176420, '[w][d][h][m][s]') 将返回值 2d 1h 0m 20s。 请注意,零周不会显示。

如果你希望显示为 0 的单位(例如 0 周),请使用大写选择符。 例如,以下代码使用 'W' 来显示零周: format_duration(176420, '[W][d][h][m][s]') 返回 0w 2d 1h 0m 20s

默认情况下,值后面的文本是选择符后跟一个空格。 您可以将其更改为您想要的任何文本。带有您的文本的选择符的格式是选择符后跟一个冒号,后跟由 '|' 字符分隔的文本段。您必须在输出中包含任何您想要的空格字符。

您可以提供一到三个文本段。

  • 如果您提供一个段,例如“[w: weeks ]”,则该段将用于所有值。

  • 如果您提供两个段,例如“[w: weeks | week ]”,则第一个段用于 0 和大于 1。第二个段用于 1。

  • 如果您提供三个段,例如“[w: weeks | week | weeks ]”,则第一个段用于 0,第二个段用于 1,第三个段用于大于 1。

第二种形式在许多语言中等同于第三种形式。

例如,选择符:

  • [w: weeks | week | weeks ] 生成 '0 weeks ''1 week ''2 weeks '

  • [w: weeks | week ] 生成 '0 weeks ''1 week ''2 weeks '

  • [w: weeks ] 生成 0 weeks '1 weeks '2 weeks '

可选的 largest_unit 参数指定模板中允许的最大单位。(可为周、天、小时、分钟和秒中的任意一个)它必须是值选择符之一。 这在需要截断较大单位的显示时很有用。

format_duration(176420, '[h][m][s]', 'd') 将返回值 1h 0m 20s 而不是 49h 0m 20s。(即只显示不超过“天”以外的部分)。

format_number

class calibre.utils.formatter_functions.BuiltinFormatNumber[源代码]

format_number(value, template) —— 将 value 解释为数字,并使用 Python 格式化模板(例如 {0:5.2f}{0:,d}${0:5,.2f})格式化该数字。 格式化模板必须以 {0: 开头,以 } 结尾,如上例所示。 例外:如果格式模板仅包含一种格式,则可以省略前导的 "{0:" 和尾随的 "}"。 有关更多示例,请参阅 模板语言Python 文档。 如果格式化失败,则返回空字符串。

human_readable

class calibre.utils.formatter_functions.BuiltinHumanReadable[源代码]

human_readable(value) —— 期望 value 是一个数字,并返回一个以 KB、MB、GB 等为单位表示该数字的字符串。

rating_to_stars

class calibre.utils.formatter_functions.BuiltinRatingToStars[源代码]

rating_to_stars(value, use_half_stars) -- 将 value 以星号 () 字符串的形式返回。 该值必须是介于 05 之间的数字。如果您希望支持自定义评分栏中的分数为半星字符,请将 use_half_stars 设置为 1

算术运算​​

add

class calibre.utils.formatter_functions.BuiltinAdd[源代码]

add(x [, y]*) -- 返回其参数的总和。 如果参数不是数字,则抛出异常。大多数情况下,您可以使用 + 运算符代替此函数。

ceiling

class calibre.utils.formatter_functions.BuiltinCeiling[源代码]

ceiling(value) —— 返回大于或等于 value 的最小整数。 如果 value 不是数字,则抛出异常。

divide

class calibre.utils.formatter_functions.BuiltinDivide[源代码]

divide(x, y) -- 返回 x / y。 如果 xy 不是数字,则抛出异常。此函数通常可以用 / 运算符代替。

floor

class calibre.utils.formatter_functions.BuiltinFloor[源代码]

floor(value) —— 返回小于或等于 value 的最大整数。 如果 value 不是数字,则抛出异常。

fractional_part

class calibre.utils.formatter_functions.BuiltinFractionalPart[源代码]

fractional_part(value) —— 返回值的小数点后的部分。 例如,fractional_part(3.14) 返回 0.14。如果 value 不是数字,则抛出异常。

mod

class calibre.utils.formatter_functions.BuiltinMod[源代码]

mod(value, y) —— 返回 value / y 余数的 floor。 如果 valuey 不是数字,则抛出异常。

multiply

class calibre.utils.formatter_functions.BuiltinMultiply[源代码]

multiply(x [, y]*) —— 返回其参数的乘积。 如果任何参数不是数字,则抛出异常。此函数通常可以用 * 运算符代替。

round

class calibre.utils.formatter_functions.BuiltinRound[源代码]

round(value) —— 返回最接近 value 的整数。 如果 value 不是数字,则抛出异常。

subtract

class calibre.utils.formatter_functions.BuiltinSubtract[源代码]

subtract(x, y) -- 返回 x - y。 如果 xy 不是数字,则抛出异常。此函数通常可以用 - 运算符代替。

递归

eval

class calibre.utils.formatter_functions.BuiltinEval[源代码]

eval(string) —— 将字符串作为程序进行求值,并传递局部变量。 这允许使用模板处理器从局部变量构造复杂的结果。在 模板程序模式 中,由于 {} 字符在模板求值之前会被解释,因此必须使用 [[ 表示 { 字符,使用 ]] 表示 } 字符。它们会自动转换。另请注意,使用模板程序模式时,此函数的参数中不能使用前缀和后缀(“|prefix|suffix”语法)。

template

class calibre.utils.formatter_functions.BuiltinTemplate[源代码]

template(x) -- x``作为模板进行评估。 评估是在其自己的上下文中完成的,这意味着变量不会在调用方和模板评估之间共享。如果没有使用常规编程模式,因为``{``和 ``}``字符是特殊的,所以必须使用``[[``表示 ``{``字符,使用]]``表示`` }``字符; 它们会自动转换。例如,template(\'[[title_sort]]\')``将评估模板 ``{title_sort}``并返回其值。 还要注意,在使用模板程序模式时,不能在此函数的参数中使用前缀和后缀(``|prefix|suffix 语法)。

遍历值

first_non_empty

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[源代码]

first_non_empty(value [, value]*) —— 返回第一个非空的 value。 如果所有值都为空,则返回空字符串。您可以设置任意数量的值。

lookup

class calibre.utils.formatter_functions.BuiltinLookup[源代码]

lookup(value, [ pattern, key, ]* else_key) —— 模式会按顺序依次与 value 进行匹配。如果某个 pattern``匹配成功,则返回由``key 指定字段的值;如果没有任何模式匹配成功,则返回由``else_key`` 指定字段的值。另请参见 switch() 函数。

switch

class calibre.utils.formatter_functions.BuiltinSwitch[源代码]

switch(value, [patternN, valueN,]+ else_value) —— 对于每个 patternN, valueN 对,检查 value 是否与正则表达式 patternN 匹配,如果匹配,则返回关联的 valueN。如果没有 patternN 匹配,则返回 else_value。您可以根据需要设置任意数量的 patternN, valueN 对。将返回第一个匹配项。

switch_if

class calibre.utils.formatter_functions.BuiltinSwitchIf[源代码]

switch_if([test_expression, value_expression,]+ else_expression) -- 对于每个 test_expression, value_expression 对,检查 test_expression 是否为 True(非空),如果是,则返回 value_expression 的结果。 如果没有 test_expression 为 True,则返回 else_expression 的结果。您可以根据需要设置任意数量的 test_expression, value_expression 对。

API of the Metadata objects

The python implementation of the template functions is passed in a Metadata object. Knowing it's API is useful if you want to define your own template functions.

class calibre.ebooks.metadata.book.base.Metadata(title, authors=('未知',), other=None, template_cache=None, formatter=None)[源代码]

A class representing all the metadata for a book. The various standard metadata fields are available as attributes of this object. You can also stick arbitrary attributes onto this object.

Metadata from custom columns should be accessed via the get() method, passing in the lookup name for the column, for example: "#mytags".

Use the is_null() method to test if a field is null.

This object also has functions to format fields into strings.

The list of standard metadata fields grows with time is in STANDARD_METADATA_FIELDS.

Please keep the method based API of this class to a minimum. Every method becomes a reserved field name.

is_null(field)[源代码]

Return True if the value of field is null in this object. 'null' means it is unknown or evaluates to False. So a title of _('Unknown') is null or a language of 'und' is null.

Be careful with numeric fields since this will return True for zero as well as None.

Also returns True if the field does not exist.

deepcopy(class_generator=<function Metadata.<lambda>>)[源代码]

Do not use this method unless you know what you are doing, if you want to create a simple clone of this object, use deepcopy_metadata() instead. Class_generator must be a function that returns an instance of Metadata or a subclass of it.

get_identifiers()[源代码]

Return a copy of the identifiers dictionary. The dict is small, and the penalty for using a reference where a copy is needed is large. Also, we don't want any manipulations of the returned dict to show up in the book.

set_identifiers(identifiers)[源代码]

Set all identifiers. Note that if you previously set ISBN, calling this method will delete it.

set_identifier(typ, val)[源代码]

If val is empty, deletes identifier of type typ

standard_field_keys()[源代码]

return a list of all possible keys, even if this book doesn't have them

custom_field_keys()[源代码]

return a list of the custom fields in this book

all_field_keys()[源代码]

All field keys known by this instance, even if their value is None

metadata_for_field(key)[源代码]

return metadata describing a standard or custom field.

all_non_none_fields()[源代码]

Return a dictionary containing all non-None metadata fields, including the custom ones.

get_standard_metadata(field, make_copy)[源代码]

return field metadata from the field if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

get_all_standard_metadata(make_copy)[源代码]

return a dict containing all the standard field metadata associated with the book.

get_all_user_metadata(make_copy)[源代码]

return a dict containing all the custom field metadata associated with the book.

get_user_metadata(field, make_copy)[源代码]

return field metadata from the object if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

set_all_user_metadata(metadata)[源代码]

store custom field metadata into the object. Field is the key name not the label

set_user_metadata(field, metadata)[源代码]

store custom field metadata for one column into the object. Field is the key name not the label

remove_stale_user_metadata(other_mi)[源代码]

Remove user metadata keys (custom column keys) if they don't exist in 'other_mi', which must be a metadata object

template_to_attribute(other, ops)[源代码]

Takes a list [(src,dest), (src,dest)], evaluates the template in the context of other, then copies the result to self[dest]. This is on a best-efforts basis. Some assignments can make no sense.

smart_update(other, replace_metadata=False)[源代码]

Merge the information in other into self. In case of conflicts, the information in other takes precedence, unless the information in other is NULL.

format_field(key, series_with_index=True)[源代码]

Returns the tuple (display_name, formatted_value)

to_html()[源代码]

A HTML representation of this object.

calibre.ebooks.metadata.book.base.STANDARD_METADATA_FIELDS

The set of standard metadata fields.


'''
All fields must have a NULL value represented as None for simple types,
an empty list/dictionary for complex types and (None, None) for cover_data
'''

SOCIAL_METADATA_FIELDS = frozenset((
    'tags',             # Ordered list
    'rating',           # A floating point number between 0 and 10
    'comments',         # A simple HTML enabled string
    'series',           # A simple string
    'series_index',     # A floating point number
    # Of the form { scheme1:value1, scheme2:value2}
    # For example: {'isbn':'123456789', 'doi':'xxxx', ... }
    'identifiers',
))

'''
The list of names that convert to identifiers when in get and set.
'''

TOP_LEVEL_IDENTIFIERS = frozenset((
    'isbn',
))

PUBLICATION_METADATA_FIELDS = frozenset((
    'title',            # title must never be None. Should be _('Unknown')
    # Pseudo field that can be set, but if not set is auto generated
    # from title and languages
    'title_sort',
    'authors',          # Ordered list. Must never be None, can be [_('Unknown')]
    'author_sort_map',  # Map of sort strings for each author
    # Pseudo field that can be set, but if not set is auto generated
    # from authors and languages
    'author_sort',
    'book_producer',
    'timestamp',        # Dates and times must be timezone aware
    'pubdate',
    'last_modified',
    'rights',
    # So far only known publication type is periodical:calibre
    # If None, means book
    'publication_type',
    'uuid',             # A UUID usually of type 4
    'languages',        # ordered list of languages in this publication
    'publisher',        # Simple string, no special semantics
    # Absolute path to image file encoded in filesystem_encoding
    'cover',
    # Of the form (format, data) where format is, e.g. 'jpeg', 'png', 'gif'...
    'cover_data',
    # Either thumbnail data, or an object with the attribute
    # image_path which is the path to an image file, encoded
    # in filesystem_encoding
    'thumbnail',
))

BOOK_STRUCTURE_FIELDS = frozenset((
    # These are used by code, Null values are None.
    'toc', 'spine', 'guide', 'manifest',
))

USER_METADATA_FIELDS = frozenset((
    # A dict of dicts similar to field_metadata. Each field description dict
    # also contains a value field with the key #value#.
    'user_metadata',
))

DEVICE_METADATA_FIELDS = frozenset((
    'device_collections',   # Ordered list of strings
    'lpath',                # Unicode, / separated
    'size',                 # In bytes
    'mime',                 # Mimetype of the book file being represented
))

CALIBRE_METADATA_FIELDS = frozenset((
    'application_id',   # An application id, currently set to the db_id.
    'db_id',            # the calibre primary key of the item.
    'formats',          # list of formats (extensions) for this book
    # a dict of user category names, where the value is a list of item names
    # from the book that are in that category
    'user_categories',
    # a dict of items to associated hyperlink
    'link_maps',
))

ALL_METADATA_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           USER_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# All fields except custom fields
STANDARD_METADATA_FIELDS = SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# Metadata fields that smart update must do special processing to copy.
SC_FIELDS_NOT_COPIED =     frozenset(('title', 'title_sort', 'authors',
                                      'author_sort', 'author_sort_map',
                                      'cover_data', 'tags', 'languages',
                                      'identifiers'))

# Metadata fields that smart update should copy only if the source is not None
SC_FIELDS_COPY_NOT_NULL =  frozenset(('device_collections', 'lpath', 'size', 'comments', 'thumbnail'))

# Metadata fields that smart update should copy without special handling
SC_COPYABLE_FIELDS =       SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS) - \
                           SC_FIELDS_NOT_COPIED.union(
                           SC_FIELDS_COPY_NOT_NULL)

SERIALIZABLE_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           USER_METADATA_FIELDS).union(
                           PUBLICATION_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS) - \
                           frozenset(('device_collections', 'formats',
                               'cover_data'))
# these are rebuilt when needed