Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import tokenize
  2. import token as token_type
  3. import keyword
  4. import io
  5.  
  6.  
  7. def tokenize_with_whitespace(readline):
  8. """
  9. like tokenize.tokenize, except it tries to yield a token for every character in the file,
  10. including non-significant whitespace.
  11. yielded values are (string, token_type) tuples.
  12. Non-significant whitespace has a token_type of None.
  13. """
  14. prev_end = (0,0)
  15. for token in tokenize.tokenize(file.readline):
  16. #check if there was whitespace between the last token and this one
  17. if token.start != prev_end:
  18. #we only really care about horizontal whitespace. Vertical whitespace is usually present in the token stream as NEWLINE or similar.
  19. if token.start[0] - prev_end[0] == 0:
  20. dx = token.start[1] - prev_end[1]
  21. yield (" "*dx, None)
  22. yield (token.string, token.type)
  23. prev_end = token.end
  24.  
  25. def apply_style(readline, style):
  26. result = []
  27. for s, type in tokenize_with_whitespace(readline):
  28. if type in style:
  29. result.append(style[type](s))
  30. else:
  31. result.append(s)
  32. return "".join(result)
  33.  
  34. # bbcode_color = lambda s, color: f"[color={color}]{s}[/color]"
  35. # bbcode_style = {
  36. # token_type.ENCODING: lambda s: "",
  37. # token_type.NAME: lambda s: bbcode_color(s, "blue") if keyword.iskeyword(s) else s,
  38. # token_type.STRING: lambda s: bbcode_color(s, "red")
  39. # }
  40.  
  41. import colorama
  42. colorama.init()
  43. colorama_style = {
  44. token_type.ENCODING: lambda s: "",
  45. token_type.NAME: lambda s: colorama.Fore.CYAN + s + colorama.Fore.RESET if keyword.iskeyword(s) else s,
  46. token_type.STRING: lambda s: colorama.Fore.RED + s + colorama.Fore.RESET
  47. }
  48.  
  49. with open("sample.py", "rb") as file:
  50. print(apply_style(file.readline, colorama_style))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement