parse.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import re
  2. import sqlite3
  3. import time
  4. ONE_GB = 2**30
  5. ONE_MB = 2**20
  6. ONE_KB = 2**10
  7. r = re.compile(r'^!(?P<bot>[a-z0-9-]+?) (?P<book>.+)\s(::INFO::|-+)\s+(?P<size>[0-9.]+\s*[BKMG]+)\s*$', re.I)
  8. # tags_re = re.compile(r'[\[\(](?P<tag>.*?)[\]\)]')
  9. def lines_to_dicts(lines):
  10. books = []
  11. for line in lines:
  12. line = line.strip()
  13. match = r.match(line)
  14. bot = match.group('bot').strip()
  15. book = match.group('book').strip()
  16. size = match.group('size').strip().lower()
  17. if 'gb' in size:
  18. size = int(float(size.replace('gb', '')) * ONE_GB)
  19. elif 'mb' in size:
  20. size = int(float(size.replace('mb', '')) * ONE_MB)
  21. elif 'kb' in size:
  22. size = int(float(size.replace('kb', '')) * ONE_KB)
  23. elif 'b' in size:
  24. size = int(float(size.replace('b', '')))
  25. books.append((bot, book, size))
  26. return books
  27. def insert_books(books):
  28. db = sqlite3.connect('books.db')
  29. c = db.cursor()
  30. entries = []
  31. c.executemany('INSERT OR IGNORE INTO books(bot, book, size) values (?,?,?)',
  32. books)
  33. db.commit()
  34. db.close()