word_tokenizer.py 2.0 KB

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