word_tokenizer.py 1.9 KB

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