Returns a new AttackedText object where the word at ``index`` is replaced with a new word.
(
self, indices: Iterable[int], new_words: Iterable[str]
)
| 330 | ] |
| 331 | |
| 332 | def replace_words_at_indices( |
| 333 | self, indices: Iterable[int], new_words: Iterable[str] |
| 334 | ) -> AttackedText: |
| 335 | """Returns a new AttackedText object where the word at ``index`` is |
| 336 | replaced with a new word.""" |
| 337 | if len(indices) != len(new_words): |
| 338 | raise ValueError( |
| 339 | f"Cannot replace {len(new_words)} words at {len(indices)} indices." |
| 340 | ) |
| 341 | words = self.words[:] |
| 342 | for i, new_word in zip(indices, new_words): |
| 343 | if not isinstance(new_word, str): |
| 344 | raise TypeError( |
| 345 | f"replace_words_at_indices requires ``str`` words, got {type(new_word)}" |
| 346 | ) |
| 347 | if (i < 0) or (i > len(words)): |
| 348 | raise ValueError(f"Cannot assign word at index {i}") |
| 349 | words[i] = new_word |
| 350 | return self.generate_new_attacked_text(words) |
| 351 | |
| 352 | def replace_word_at_index(self, index: int, new_word: str) -> AttackedText: |
| 353 | """Returns a new AttackedText object where the word at ``index`` is |