Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. #sample.py
  2. import os
  3. with open("test.py") as file:
  4. for line in file:
  5. print(line)
  6.  
  7. #main.py
  8. import tokenize
  9. import keyword
  10. import io
  11.  
  12. colored_tokens = []
  13. with open("sample.py", "rb") as file:
  14. for token in tokenize.tokenize(file.readline):
  15. if token.type == 59: #encoding. Skip.
  16. pass
  17. elif token.type == 1: #name, e.g. a variable or keyword
  18. if keyword.iskeyword(token.string):
  19. colored_tokens.append(f"[color=blue]{token.string}[/color]")
  20. else:
  21. colored_tokens.append(token.string)
  22. elif token.type == 3: #string literal
  23. colored_tokens.append(f"[color=red]{token.string}[/color]")
  24. else:
  25. colored_tokens.append(token.string)
  26.  
  27. print("".join(colored_tokens))
  28.  
  29. #output:
  30. [color=blue]import[/color]os
  31. [color=blue]with[/color]open([color=red]"test.py"[/color])[color=blue]as[/color]file:
  32. [color=blue]for[/color]line[color=blue]in[/color]file:
  33. print(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement