From 95b1e4c3c08a5d2ff150badd037524e716e058b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Sun, 23 Jun 2019 22:41:03 +0200 Subject: [PATCH] implement R// format option (#318) --- gallery_dl/util.py | 16 ++++++++++++++++ test/test_results.py | 1 - test/test_util.py | 9 +++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index 1c2b160662..5c0ae418f6 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -341,6 +341,7 @@ class Formatter(): - "c": calls str.capitalize - "C": calls string.capwords - "U": calls urllib.parse.unquote + - "S": calls util.to_string() - Example: {f!l} -> "example"; {f!u} -> "EXAMPLE" Extra Format Specifiers: @@ -359,6 +360,10 @@ class Formatter(): - "J/": Joins elements of a list (or string) using Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"]) + + - "R//": + Replaces all occurrences of with + Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r") """ CONVERSIONS = { "l": str.lower, @@ -417,6 +422,8 @@ def _field_access(self, field_name, format_spec, conversion): func = self._format_maxlen elif format_spec[0] == "J": func = self._format_join + elif format_spec[0] == "R": + func = self._format_replace else: func = self._format_default fmt = func(format_spec) @@ -484,6 +491,15 @@ def wrap(obj): separator = separator[1:] return wrap + @staticmethod + def _format_replace(format_spec): + def wrap(obj): + obj = obj.replace(old, new) + return format(obj, format_spec) + old, new, format_spec = format_spec.split("/", 2) + old = old[1:] + return wrap + @staticmethod def _format_default(format_spec): def wrap(obj): diff --git a/test/test_results.py b/test/test_results.py index ad7f091262..6a785c88f4 100644 --- a/test/test_results.py +++ b/test/test_results.py @@ -27,7 +27,6 @@ # temporary issues, etc. BROKEN = { "mangapark", - "pixnet", } diff --git a/test/test_util.py b/test/test_util.py index 87197c4604..815b2d8db4 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -264,6 +264,15 @@ def test_join(self): self._run_test("{a:J/}" , self.kwdict["a"]) self._run_test("{a:J, /}" , ", ".join(self.kwdict["a"])) + def test_replace(self): + self._run_test("{a:Rh/C/}" , "CElLo wOrLd") + self._run_test("{a!l:Rh/C/}", "Cello world") + self._run_test("{a!u:Rh/C/}", "HELLO WORLD") + + self._run_test("{a!l:Rl/_/}", "he__o wor_d") + self._run_test("{a!l:Rl//}" , "heo word") + self._run_test("{name:Rame/othing/}", "Nothing") + def _run_test(self, format_string, result, default=None): formatter = util.Formatter(format_string, default) output = formatter.format_map(self.kwdict)