社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

[精华] Python输出py文件模拟代码高亮

BeginMan • 10 年前 • 4688 次点击  

此程序十分简单,模拟的过程中简易的处理了Py语法对应的高亮,并输出行号。代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#! /usr/bin/env python
# coding:utf-8
# **************************************
# Function: python 打开Py文件高亮显示
# Version:  1.0
# Author:   'beginman'
# **************************************
# py colorama:https://pypi.python.org/pypi/colorama
import os
import random
from colorama import *
init(autoreset=True)
COLOR = [Fore.RED, Fore.GREEN, Fore.BLUE, Fore.BLACK, Fore.YELLOW,
         Fore.MAGENTA, Fore.CYAN, Fore.WHITE, Fore.RESET]
BACK = Back.GREEN                               # 行号

Syna = {
    'def': Fore.RED+Style.BRIGHT,
    'class': Fore.GREEN+Style.BRIGHT,
    '"""': Fore.YELLOW+Style.BRIGHT,
    "'''": Fore.YELLOW+Style.BRIGHT,
    'import': Fore.YELLOW,
    'from': Fore.YELLOW,
    'for': Fore.MAGENTA+Style.BRIGHT,
    'elif': Fore.MAGENTA+Style.BRIGHT,
    'else': Fore.MAGENTA+Style.BRIGHT,
    'print': Fore.CYAN,
    '#': Fore.GREEN
    }


def PrintFile(path):
    """Print file"""
    f = open(path)
    count = 1
    for line in f.readlines():
        sy_list = [i for i in Syna.items()]
        RANDOM_COLOR = [s[1] for s in sy_list if line.strip().startswith(s[0])]
        RANDOM_COLOR = RANDOM_COLOR[0] if RANDOM_COLOR else random.choice(COLOR)

        n = u'☺ %s   ' % count if count<10 else u'☺ %s  ' % count
        linenum = Style.NORMAL+BACK + n
        count += 1
        print linenum,RANDOM_COLOR + line.strip()


def GetPath():
    """choice file"""
    while True:
        file = raw_input(u'请输入指定文件:')
        if os.path.isfile(file):
            break
    return file

def main():
    PrintFile(GetPath())

if __name__ == '__main__':
    main()

效果如下:

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/452
 
4688 次点击  
文章 [ 1 ]  |  最新文章 10 年前