word_tokenizer.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from pathlib import Path
  2. from typing import Iterable
  3. from typing import List
  4. from typing import Union
  5. import warnings
  6. from typeguard import check_argument_types
  7. from funasr.text.abs_tokenizer import AbsTokenizer
  8. class WordTokenizer(AbsTokenizer):
  9. def __init__(
  10. self,
  11. delimiter: str = None,
  12. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  13. remove_non_linguistic_symbols: bool = False,
  14. ):
  15. assert check_argument_types()
  16. self.delimiter = delimiter
  17. if not remove_non_linguistic_symbols and non_linguistic_symbols is not None:
  18. warnings.warn(
  19. "non_linguistic_symbols is only used "
  20. "when remove_non_linguistic_symbols = True"
  21. )
  22. if non_linguistic_symbols is None:
  23. self.non_linguistic_symbols = set()
  24. elif isinstance(non_linguistic_symbols, (Path, str)):
  25. non_linguistic_symbols = Path(non_linguistic_symbols)
  26. try:
  27. with non_linguistic_symbols.open("r", encoding="utf-8") as f:
  28. self.non_linguistic_symbols = set(line.rstrip() for line in f)
  29. except FileNotFoundError:
  30. warnings.warn(f"{non_linguistic_symbols} doesn't exist.")
  31. self.non_linguistic_symbols = set()
  32. else:
  33. self.non_linguistic_symbols = set(non_linguistic_symbols)
  34. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  35. def __repr__(self):
  36. return f'{self.__class__.__name__}(delimiter="{self.delimiter}")'
  37. def text2tokens(self, line: str) -> List[str]:
  38. tokens = []
  39. for t in line.split(self.delimiter):
  40. if self.remove_non_linguistic_symbols and t in self.non_linguistic_symbols:
  41. continue
  42. tokens.append(t)
  43. return tokens
  44. def tokens2text(self, tokens: Iterable[str]) -> str:
  45. if self.delimiter is None:
  46. delimiter = " "
  47. else:
  48. delimiter = self.delimiter
  49. return delimiter.join(tokens)