prep_text8.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. # BSD 3-Clause License
  4. #
  5. # Copyright (c) 2017,
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. #
  11. # * Redistributions of source code must retain the above copyright notice, this
  12. # list of conditions and the following disclaimer.
  13. #
  14. # * Redistributions in binary form must reproduce the above copyright notice,
  15. # this list of conditions and the following disclaimer in the documentation
  16. # and/or other materials provided with the distribution.
  17. #
  18. # * Neither the name of the copyright holder nor the names of its
  19. # contributors may be used to endorse or promote products derived from
  20. # this software without specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  23. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  24. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  25. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  26. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  27. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  28. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  29. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  30. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. import os
  33. import sys
  34. import zipfile
  35. from io import open
  36. if os.path.exists('train.txt'):
  37. print('Tokenized text8 already exists - skipping processing')
  38. sys.exit()
  39. data = zipfile.ZipFile('text8.zip').extractall()
  40. data = open('text8', 'r', encoding='utf-8').read()
  41. print('Length of text8: {}'.format(len(data)))
  42. num_test_chars = 5000000
  43. train_data = data[: -2 * num_test_chars]
  44. valid_data = data[-2 * num_test_chars: -num_test_chars]
  45. test_data = data[-num_test_chars:]
  46. for fn, part in [('train.txt', train_data), ('valid.txt', valid_data), ('test.txt', test_data)]:
  47. print('{} will have {} bytes'.format(fn, len(part)))
  48. print('- Tokenizing...')
  49. # Change space ' ' to underscore '_'
  50. part_str = ' '.join(['_' if c == ' ' else c for c in part.strip()])
  51. print('- Writing...')
  52. f = open(fn, 'w').write(part_str)
  53. f = open(fn + '.raw', 'w', encoding='utf-8').write(part)