Skip to content

transforms

transforms #

This file implements the building blocks for transforming a collection of input strings to the desired format in order to calculate the WER of CER.

In principle, for word error rate calculations, every string of a sentence needs to be collapsed into a list of strings, where each string is a single word. This is done with transforms.ReduceToListOfListOfWords. A composition of multiple transformations must therefore always end with transforms.ReduceToListOfListOfWords.

For the character error rate, every string of a sentence also needs to be collapsed into a list of strings, but here each string is a single character. This is done with transforms.ReduceToListOfListOfChars. Similarly, a composition of multiple transformations must therefore also always end with transforms.ReduceToListOfListOfChars.

AbstractTransform #

Bases: object

The base class of a Transform.

Source code in jiwer/transforms.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class AbstractTransform(object):
    """
    The base class of a Transform.
    """

    def __call__(self, sentences: Union[str, List[str]]):
        """
        Transforms one or more strings.

        Args:
            sentences: The strings to transform.

        Returns:
            (Union[str, List[str]]): The transformed strings.

        """
        if isinstance(sentences, str):
            return self.process_string(sentences)
        elif isinstance(sentences, list):
            return self.process_list(sentences)
        else:
            raise ValueError(
                "input {} was expected to be a string or list of strings".format(
                    sentences
                )
            )

    def process_string(self, s: str):
        raise NotImplementedError()

    def process_list(self, inp: List[str]):
        return [self.process_string(s) for s in inp]

__call__ #

__call__(sentences)

Transforms one or more strings.

Parameters:

Name Type Description Default
sentences Union[str, List[str]]

The strings to transform.

required

Returns:

Type Description
Union[str, List[str]]

The transformed strings.

Source code in jiwer/transforms.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __call__(self, sentences: Union[str, List[str]]):
    """
    Transforms one or more strings.

    Args:
        sentences: The strings to transform.

    Returns:
        (Union[str, List[str]]): The transformed strings.

    """
    if isinstance(sentences, str):
        return self.process_string(sentences)
    elif isinstance(sentences, list):
        return self.process_list(sentences)
    else:
        raise ValueError(
            "input {} was expected to be a string or list of strings".format(
                sentences
            )
        )

Compose #

Bases: object

Chain multiple transformations back-to-back to create a pipeline combining multiple transformations.

Note that each transformation needs to end with either ReduceToListOfListOfWords or ReduceToListOfListOfChars, depending on whether word error rate, or character error rate is desired.

Example
import jiwer

jiwer.Compose([
    jiwer.RemoveMultipleSpaces(),
    jiwer.ReduceToListOfListOfWords()
])
Source code in jiwer/transforms.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
class Compose(object):
    """
    Chain multiple transformations back-to-back to create a pipeline combining multiple
    transformations.

    Note that each transformation needs to end with either `ReduceToListOfListOfWords`
    or `ReduceToListOfListOfChars`, depending on whether word error rate,
    or character error rate is desired.

    Example:
        ```python3
        import jiwer

        jiwer.Compose([
            jiwer.RemoveMultipleSpaces(),
            jiwer.ReduceToListOfListOfWords()
        ])
        ```
    """

    def __init__(self, transforms: List[AbstractTransform]):
        """

        Args:
            transforms: The list of transformations to chain.
        """
        self.transforms = transforms

    def __call__(self, text):
        for tr in self.transforms:
            text = tr(text)

        return text

__init__ #

__init__(transforms)

Parameters:

Name Type Description Default
transforms List[AbstractTransform]

The list of transformations to chain.

required
Source code in jiwer/transforms.py
120
121
122
123
124
125
126
def __init__(self, transforms: List[AbstractTransform]):
    """

    Args:
        transforms: The list of transformations to chain.
    """
    self.transforms = transforms

ExpandCommonEnglishContractions #

Bases: AbstractTransform

Replace common contractions such as let's to let us.

Currently, this method will perform the following replacements. Note that is used to indicate a space () to get around markdown rendering constrains.

Contraction transformed into
won't ␣will not
can't ␣can not
let's ␣let us
n't ␣not
're ␣are
's ␣is
'd ␣would
'll ␣will
't ␣not
've ␣have
'm ␣am
Example
import jiwer

sentences = ["she'll make sure you can't make it", "let's party!"]

print(jiwer.ExpandCommonEnglishContractions()(sentences))
# prints: ["she will make sure you can not make it", "let us party!"]
Source code in jiwer/transforms.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
class ExpandCommonEnglishContractions(AbstractTransform):
    """
    Replace common contractions such as `let's` to `let us`.

    Currently, this method will perform the following replacements. Note that `␣` is
     used to indicate a space (` `) to get around markdown rendering constrains.

    | Contraction   | transformed into |
    | ------------- |:----------------:|
    | `won't`       | `␣will not`      |
    | `can't`       | `␣can not`       |
    | `let's`       | `␣let us`        |
    | `n't`         | `␣not`           |
    | `'re`         | `␣are`           |
    | `'s`          | `␣is`            |
    | `'d`          | `␣would`         |
    | `'ll`         | `␣will`          |
    | `'t`          | `␣not`           |
    | `'ve`         | `␣have`          |
    | `'m`          | `␣am`            |

    Example:
        ```python
        import jiwer

        sentences = ["she'll make sure you can't make it", "let's party!"]

        print(jiwer.ExpandCommonEnglishContractions()(sentences))
        # prints: ["she will make sure you can not make it", "let us party!"]
        ```

    """

    def process_string(self, s: str):
        # definitely a non exhaustive list

        # specific words
        s = re.sub(r"won't", "will not", s)
        s = re.sub(r"can\'t", "can not", s)
        s = re.sub(r"let\'s", "let us", s)

        # general attachments
        s = re.sub(r"n\'t", " not", s)
        s = re.sub(r"\'re", " are", s)
        s = re.sub(r"\'s", " is", s)
        s = re.sub(r"\'d", " would", s)
        s = re.sub(r"\'ll", " will", s)
        s = re.sub(r"\'t", " not", s)
        s = re.sub(r"\'ve", " have", s)
        s = re.sub(r"\'m", " am", s)

        return s

ReduceToListOfListOfChars #

Bases: AbstractTransform

Transforms a single input sentence, or a list of input sentences, into a list with lists of characters, which is the expected format for calculating the edit operations between two input sentences on a character-level.

A sentence is assumed to be a string. Each string is expected to contain only a single sentence.

Example
import jiwer

sentences = ["hi", "this is an example"]

print(jiwer.ReduceToListOfListOfChars()(sentences))
# prints: [['h', 'i'], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 'e', 'x', 'a', 'm', 'p', 'l', 'e']]
Source code in jiwer/transforms.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
class ReduceToListOfListOfChars(AbstractTransform):
    """
    Transforms a single input sentence, or a list of input sentences, into
    a list with lists of characters, which is the expected format for calculating the
    edit operations between two input sentences on a character-level.

    A sentence is assumed to be a string. Each string is expected to contain only a
    single sentence.

    Example:
        ```python
        import jiwer

        sentences = ["hi", "this is an example"]

        print(jiwer.ReduceToListOfListOfChars()(sentences))
        # prints: [['h', 'i'], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 'e', 'x', 'a', 'm', 'p', 'l', 'e']]
        ```
    """

    def process_string(self, s: str):
        return [[w for w in s]]

    def process_list(self, inp: List[str]):
        sentence_collection = []

        for sentence in inp:
            list_of_words = self.process_string(sentence)[0]

            sentence_collection.append(list_of_words)

        if len(sentence_collection) == 0:
            return [[]]

        return sentence_collection

ReduceToListOfListOfWords #

Bases: AbstractTransform

Transforms a single input sentence, or a list of input sentences, into a list with lists of words, which is the expected format for calculating the edit operations between two input sentences on a word-level.

A sentence is assumed to be a string, where words are delimited by a token (such as , space). Each string is expected to contain only a single sentence. Empty strings (no output) are removed for the list.

Example
import jiwer

sentences = ["hi", "this is an example"]

print(jiwer.ReduceToListOfListOfWords()(sentences))
# prints: [['hi'], ['this', 'is', 'an, 'example']]
Source code in jiwer/transforms.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class ReduceToListOfListOfWords(AbstractTransform):
    """
    Transforms a single input sentence, or a list of input sentences, into
    a list with lists of words, which is the expected format for calculating the
    edit operations between two input sentences on a word-level.

    A sentence is assumed to be a string, where words are delimited by a token
    (such as ` `, space). Each string is expected to contain only a single sentence.
    Empty strings (no output) are removed for the list.

    Example:
        ```python
        import jiwer

        sentences = ["hi", "this is an example"]

        print(jiwer.ReduceToListOfListOfWords()(sentences))
        # prints: [['hi'], ['this', 'is', 'an, 'example']]
        ```
    """

    def __init__(self, word_delimiter: str = " "):
        """
        Args:
            word_delimiter: the character which delimits words. Default is ` ` (space).
        """
        self.word_delimiter = word_delimiter

    def process_string(self, s: str):
        return [[w for w in s.split(self.word_delimiter) if len(w) >= 1]]

    def process_list(self, inp: List[str]):
        sentence_collection = []

        for sentence in inp:
            list_of_words = self.process_string(sentence)[0]

            sentence_collection.append(list_of_words)

        if len(sentence_collection) == 0:
            return [[]]

        return sentence_collection

__init__ #

__init__(word_delimiter=' ')

Parameters:

Name Type Description Default
word_delimiter str

the character which delimits words. Default is (space).

' '
Source code in jiwer/transforms.py
171
172
173
174
175
176
def __init__(self, word_delimiter: str = " "):
    """
    Args:
        word_delimiter: the character which delimits words. Default is ` ` (space).
    """
    self.word_delimiter = word_delimiter

ReduceToSingleSentence #

Bases: AbstractTransform

Transforms multiple sentences into a single sentence. This operation can be useful when the number of reference and hypothesis sentences differ, and you want to do a minimal alignment over these lists. Note that this creates an invariance: wer([a, b], [a, b]) might not be equal to wer([b, a], [b, a]).

Example
import jiwer

sentences = ["hi", "this is an example"]

print(jiwer.ReduceToSingleSentence()(sentences))
# prints: ['hi this is an example']
Source code in jiwer/transforms.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
class ReduceToSingleSentence(AbstractTransform):
    """
    Transforms multiple sentences into a single sentence.
    This operation can be useful when the number of reference and hypothesis sentences
    differ, and you want to do a minimal alignment over these lists.
    Note that this creates an invariance: `wer([a, b], [a, b])` might not be equal to
    `wer([b, a], [b, a])`.

    Example:
        ```python3
        import jiwer

        sentences = ["hi", "this is an example"]

        print(jiwer.ReduceToSingleSentence()(sentences))
        # prints: ['hi this is an example']
        ```
    """

    def __init__(self, word_delimiter: str = " "):
        """
        :param word_delimiter: the character which delimits words. Default is ` ` (space).
        """
        self.word_delimiter = word_delimiter

    def process_string(self, s: str):
        return s

    def process_list(self, inp: List[str]):
        filtered_inp = [i for i in inp if len(i) >= 1]

        if len(filtered_inp) == 0:
            return []
        else:
            return ["{}".format(self.word_delimiter).join(filtered_inp)]

__init__ #

__init__(word_delimiter=' ')

:param word_delimiter: the character which delimits words. Default is (space).

Source code in jiwer/transforms.py
251
252
253
254
255
def __init__(self, word_delimiter: str = " "):
    """
    :param word_delimiter: the character which delimits words. Default is ` ` (space).
    """
    self.word_delimiter = word_delimiter

RemoveEmptyStrings #

Bases: AbstractTransform

Remove empty strings from a list of strings.

Example
import jiwer

sentences = ["", "this is an example", " ",  "                "]

print(jiwer.RemoveEmptyStrings()(sentences))
# prints: ['this is an example']
Source code in jiwer/transforms.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
class RemoveEmptyStrings(AbstractTransform):
    """
    Remove empty strings from a list of strings.

    Example:
        ```python
        import jiwer

        sentences = ["", "this is an example", " ",  "                "]

        print(jiwer.RemoveEmptyStrings()(sentences))
        # prints: ['this is an example']
        ```
    """

    def process_string(self, s: str):
        return s.strip()

    def process_list(self, inp: List[str]):
        return [s for s in inp if self.process_string(s) != ""]

RemoveKaldiNonWords #

Bases: AbstractTransform

Remove any word between [] and <>. This can be useful when working with hypotheses from the Kaldi project, which can output non-words such as [laugh] and <unk>.

Example
import jiwer

sentences = ["you <unk> like [laugh]"]

print(jiwer.RemoveKaldiNonWords()(sentences))

# prints: ["you  like "]
# note the extra spaces
Source code in jiwer/transforms.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
class RemoveKaldiNonWords(AbstractTransform):
    """
    Remove any word between `[]` and `<>`. This can be useful when working
    with hypotheses from the Kaldi project, which can output non-words such as
    `[laugh]` and `<unk>`.

    Example:
        ```python
        import jiwer

        sentences = ["you <unk> like [laugh]"]

        print(jiwer.RemoveKaldiNonWords()(sentences))

        # prints: ["you  like "]
        # note the extra spaces
        ```
    """

    def process_string(self, s: str):
        return re.sub(r"[<\[][^>\]]*[>\]]", "", s)

RemoveMultipleSpaces #

Bases: AbstractTransform

Filter out multiple spaces between words.

Example
import jiwer

sentences = ["this is   an   example ", "  hello goodbye  ", "  "]

print(jiwer.RemoveMultipleSpaces()(sentences))
# prints: ['this is an example ', " hello goodbye ", " "]
# note that there are still trailing spaces
Source code in jiwer/transforms.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
class RemoveMultipleSpaces(AbstractTransform):
    """
    Filter out multiple spaces between words.

    Example:
        ```python
        import jiwer

        sentences = ["this is   an   example ", "  hello goodbye  ", "  "]

        print(jiwer.RemoveMultipleSpaces()(sentences))
        # prints: ['this is an example ', " hello goodbye ", " "]
        # note that there are still trailing spaces
        ```

    """

    def process_string(self, s: str):
        return re.sub(r"\s\s+", " ", s)

    def process_list(self, inp: List[str]):
        return [self.process_string(s) for s in inp]

RemovePunctuation #

Bases: BaseRemoveTransform

This transform filters out punctuation. The punctuation characters are defined as all unicode characters whose category name starts with P. See here for more information. Example:

import jiwer

sentences = ["this is an example!", "hello. goodbye"]

print(jiwer.RemovePunctuation()(sentences))
# prints: ['this is an example', "hello goodbye"]

Source code in jiwer/transforms.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class RemovePunctuation(BaseRemoveTransform):
    """
    This transform filters out punctuation. The punctuation characters are defined as
    all unicode characters whose category name starts with `P`.
    See [here](https://www.unicode.org/reports/tr44/#General_Category_Values) for more
    information.
    Example:
        ```python
        import jiwer

        sentences = ["this is an example!", "hello. goodbye"]

        print(jiwer.RemovePunctuation()(sentences))
        # prints: ['this is an example', "hello goodbye"]
        ```
    """

    def __init__(self):
        punctuation_characters = _get_punctuation_characters()
        super().__init__(punctuation_characters)

RemoveSpecificWords #

Bases: SubstituteWords

Can be used to filter out certain words. As words are replaced with a character, make sure to that RemoveMultipleSpaces, Strip() and RemoveEmptyStrings are present in the composition after RemoveSpecificWords.

Example
import jiwer

sentences = ["yhe awesome", "the apple is not a pear", "yhe"]

print(jiwer.RemoveSpecificWords(["yhe", "the", "a"])(sentences))
# prints: ['  awesome', '  apple is not   pear', ' ']
# note the extra spaces
Source code in jiwer/transforms.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
class RemoveSpecificWords(SubstituteWords):
    """
    Can be used to filter out certain words.
    As words are replaced with a ` ` character, make sure to that
    `RemoveMultipleSpaces`, `Strip()` and `RemoveEmptyStrings` are present
    in the composition _after_ `RemoveSpecificWords`.

    Example:
        ```python
        import jiwer

        sentences = ["yhe awesome", "the apple is not a pear", "yhe"]

        print(jiwer.RemoveSpecificWords(["yhe", "the", "a"])(sentences))
        # prints: ['  awesome', '  apple is not   pear', ' ']
        # note the extra spaces
        ```
    """

    def __init__(self, words_to_remove: List[str]):
        """
        Args:
            words_to_remove: List of words to remove.
        """
        mapping = {word: " " for word in words_to_remove}

        super().__init__(mapping)

__init__ #

__init__(words_to_remove)

Parameters:

Name Type Description Default
words_to_remove List[str]

List of words to remove.

required
Source code in jiwer/transforms.py
357
358
359
360
361
362
363
364
def __init__(self, words_to_remove: List[str]):
    """
    Args:
        words_to_remove: List of words to remove.
    """
    mapping = {word: " " for word in words_to_remove}

    super().__init__(mapping)

RemoveWhiteSpace #

Bases: BaseRemoveTransform

This transform filters out white space characters. Note that by default space () is also removed, which will make it impossible to split a sentence into a list of words by using ReduceToListOfListOfWords or ReduceToSingleSentence. This can be prevented by replacing all whitespace with the space character. If so, make sure that jiwer.RemoveMultipleSpaces, Strip() and RemoveEmptyStrings are present in the composition after RemoveWhiteSpace.

Example
import jiwer

sentences = ["this is an example", "hello world "]

print(jiwer.RemoveWhiteSpace()(sentences))
# prints: ["thisisanexample", "helloworld"]

print(jiwer.RemoveWhiteSpace(replace_by_space=True)(sentences))
# prints: ["this is an example", "hello world  "]
# note the trailing spaces
Source code in jiwer/transforms.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
class RemoveWhiteSpace(BaseRemoveTransform):
    """
    This transform filters out white space characters.
    Note that by default space (` `) is also removed, which will make it impossible to
    split a sentence into a list of words by using `ReduceToListOfListOfWords` or
    `ReduceToSingleSentence`.
    This can be prevented by replacing all whitespace with the space character.
    If so, make sure that `jiwer.RemoveMultipleSpaces`,
    `Strip()` and `RemoveEmptyStrings` are present in the composition _after_
    `RemoveWhiteSpace`.

    Example:
        ```python
        import jiwer

        sentences = ["this is an example", "hello world\t"]

        print(jiwer.RemoveWhiteSpace()(sentences))
        # prints: ["thisisanexample", "helloworld"]

        print(jiwer.RemoveWhiteSpace(replace_by_space=True)(sentences))
        # prints: ["this is an example", "hello world  "]
        # note the trailing spaces
        ```
    """

    def __init__(self, replace_by_space: bool = False):
        """

        Args:
            replace_by_space: every white space character is replaced with a space (` `)
        """
        characters = [c for c in string.whitespace]

        if replace_by_space:
            replace_token = " "
        else:
            replace_token = ""

        super().__init__(characters, replace_token=replace_token)

__init__ #

__init__(replace_by_space=False)

Parameters:

Name Type Description Default
replace_by_space bool

every white space character is replaced with a space ()

False
Source code in jiwer/transforms.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def __init__(self, replace_by_space: bool = False):
    """

    Args:
        replace_by_space: every white space character is replaced with a space (` `)
    """
    characters = [c for c in string.whitespace]

    if replace_by_space:
        replace_token = " "
    else:
        replace_token = ""

    super().__init__(characters, replace_token=replace_token)

Strip #

Bases: AbstractTransform

Removes all leading and trailing spaces.

Example
import jiwer

sentences = [" this is an example ", "  hello goodbye  ", "  "]

print(jiwer.Strip()(sentences))
# prints: ['this is an example', "hello goodbye", ""]
# note that there is an empty string left behind which might need to be cleaned up
Source code in jiwer/transforms.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
class Strip(AbstractTransform):
    """
    Removes all leading and trailing spaces.

    Example:
        ```python
        import jiwer

        sentences = [" this is an example ", "  hello goodbye  ", "  "]

        print(jiwer.Strip()(sentences))
        # prints: ['this is an example', "hello goodbye", ""]
        # note that there is an empty string left behind which might need to be cleaned up
        ```
    """

    def process_string(self, s: str):
        return s.strip()

SubstituteRegexes #

Bases: AbstractTransform

Transform strings by substituting substrings matching regex expressions into another substring.

Example
import jiwer

sentences = ["is the world doomed or loved?", "edibles are allegedly cultivated"]

# note: the regex string "(\w+)ed", matches every word ending in 'ed',
# and "" stands for the first group ('\w+). It therefore removes 'ed' in every match.
print(jiwer.SubstituteRegexes({r"doom": r"sacr", r"(\w+)ed": r""})(sentences))

# prints: ["is the world sacr or lov?", "edibles are allegedly cultivat"]
Source code in jiwer/transforms.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class SubstituteRegexes(AbstractTransform):
    """
    Transform strings by substituting substrings matching regex expressions into
    another substring.

    Example:
        ```python
        import jiwer

        sentences = ["is the world doomed or loved?", "edibles are allegedly cultivated"]

        # note: the regex string "\b(\w+)ed\b", matches every word ending in 'ed',
        # and "\1" stands for the first group ('\w+). It therefore removes 'ed' in every match.
        print(jiwer.SubstituteRegexes({r"doom": r"sacr", r"\b(\w+)ed\b": r"\1"})(sentences))

        # prints: ["is the world sacr or lov?", "edibles are allegedly cultivat"]
        ```
    """

    def __init__(self, substitutions: Mapping[str, str]):
        """

        Args:
            substitutions: a mapping of regex expressions to replacement strings.
        """
        self.substitutions = substitutions

    def process_string(self, s: str):
        for key, value in self.substitutions.items():
            s = re.sub(key, value, s)

        return s

__init__ #

__init__(substitutions)

Parameters:

Name Type Description Default
substitutions Mapping[str, str]

a mapping of regex expressions to replacement strings.

required
Source code in jiwer/transforms.py
288
289
290
291
292
293
294
def __init__(self, substitutions: Mapping[str, str]):
    """

    Args:
        substitutions: a mapping of regex expressions to replacement strings.
    """
    self.substitutions = substitutions

SubstituteWords #

Bases: AbstractTransform

This transform can be used to replace a word into another word. Note that the whole word is matched. If the word you're attempting to substitute is a substring of another word it will not be affected. For example, if you're substituting foo into bar, the word foobar will NOT be substituted into barbar.

Example
import jiwer

sentences = ["you're pretty", "your book", "foobar"]

print(jiwer.SubstituteWords({"pretty": "awesome", "you": "i", "'re": " am", 'foo': 'bar'})(sentences))

# prints: ["i am awesome", "your book", "foobar"]
Source code in jiwer/transforms.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class SubstituteWords(AbstractTransform):
    """
    This transform can be used to replace a word into another word.
    Note that the whole word is matched. If the word you're attempting to substitute
    is a substring of another word it will not be affected.
    For example, if you're substituting `foo` into `bar`, the word `foobar` will NOT
    be substituted into `barbar`.

    Example:
        ```python
        import jiwer

        sentences = ["you're pretty", "your book", "foobar"]

        print(jiwer.SubstituteWords({"pretty": "awesome", "you": "i", "'re": " am", 'foo': 'bar'})(sentences))

        # prints: ["i am awesome", "your book", "foobar"]
        ```

    """

    def __init__(self, substitutions: Mapping[str, str]):
        """
        Args:
            substitutions: A mapping of words to replacement words.
        """
        self.substitutions = substitutions

    def process_string(self, s: str):
        for key, value in self.substitutions.items():
            s = re.sub(r"\b{}\b".format(re.escape(key)), value, s)

        return s

__init__ #

__init__(substitutions)

Parameters:

Name Type Description Default
substitutions Mapping[str, str]

A mapping of words to replacement words.

required
Source code in jiwer/transforms.py
324
325
326
327
328
329
def __init__(self, substitutions: Mapping[str, str]):
    """
    Args:
        substitutions: A mapping of words to replacement words.
    """
    self.substitutions = substitutions

ToLowerCase #

Bases: AbstractTransform

Convert every character into lowercase. Example:

import jiwer

sentences = ["You're PRETTY"]

print(jiwer.ToLowerCase()(sentences))

# prints: ["you're pretty"]

Source code in jiwer/transforms.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
class ToLowerCase(AbstractTransform):
    """
    Convert every character into lowercase.
    Example:
        ```python
        import jiwer

        sentences = ["You're PRETTY"]

        print(jiwer.ToLowerCase()(sentences))

        # prints: ["you're pretty"]
        ```
    """

    def process_string(self, s: str):
        return s.lower()

ToUpperCase #

Bases: AbstractTransform

Convert every character to uppercase.

Example
import jiwer

sentences = ["You're amazing"]

print(jiwer.ToUpperCase()(sentences))

# prints: ["YOU'RE AMAZING"]
Source code in jiwer/transforms.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
class ToUpperCase(AbstractTransform):
    """
    Convert every character to uppercase.

    Example:
        ```python
        import jiwer

        sentences = ["You're amazing"]

        print(jiwer.ToUpperCase()(sentences))

        # prints: ["YOU'RE AMAZING"]
        ```
    """

    def process_string(self, s: str):
        return s.upper()