You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 2.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. from typing import Union, Dict
  3. def check_dataloader_paths(paths:Union[str, Dict[str, str]])->Dict[str, str]:
  4. """
  5. 检查传入dataloader的文件的合法性。如果为合法路径,将返回至少包含'train'这个key的dict。类似于下面的结果
  6. {
  7. 'train': '/some/path/to/', # 一定包含,建词表应该在这上面建立,剩下的其它文件应该只需要处理并index。
  8. 'test': 'xxx' # 可能有,也可能没有
  9. ...
  10. }
  11. 如果paths为不合法的,将直接进行raise相应的错误
  12. :param paths: 路径. 可以为一个文件路径(则认为该文件就是train的文件); 可以为一个文件目录,将在该目录下寻找train(文件名
  13. 中包含train这个字段), test.txt, dev.txt; 可以为一个dict, 则key是用户自定义的某个文件的名称,value是这个文件的路径。
  14. :return:
  15. """
  16. if isinstance(paths, str):
  17. if os.path.isfile(paths):
  18. return {'train': paths}
  19. elif os.path.isdir(paths):
  20. filenames = os.listdir(paths)
  21. files = {}
  22. for filename in filenames:
  23. path_pair = None
  24. if 'train' in filename:
  25. path_pair = ('train', filename)
  26. if 'dev' in filename:
  27. if path_pair:
  28. raise Exception("File:{} in {} contains bot `{}` and `dev`.".format(filename, paths, path_pair[0]))
  29. path_pair = ('dev', filename)
  30. if 'test' in filename:
  31. if path_pair:
  32. raise Exception("File:{} in {} contains bot `{}` and `test`.".format(filename, paths, path_pair[0]))
  33. path_pair = ('test', filename)
  34. if path_pair:
  35. files[path_pair[0]] = os.path.join(paths, path_pair[1])
  36. return files
  37. else:
  38. raise FileNotFoundError(f"{paths} is not a valid file path.")
  39. elif isinstance(paths, dict):
  40. if paths:
  41. if 'train' not in paths:
  42. raise KeyError("You have to include `train` in your dict.")
  43. for key, value in paths.items():
  44. if isinstance(key, str) and isinstance(value, str):
  45. if not os.path.isfile(value):
  46. raise TypeError(f"{value} is not a valid file.")
  47. else:
  48. raise TypeError("All keys and values in paths should be str.")
  49. return paths
  50. else:
  51. raise ValueError("Empty paths is not allowed.")
  52. else:
  53. raise TypeError(f"paths only supports str and dict. not {type(paths)}.")