首先是白嫖以下大神的代碼:統計python代碼行數小工具_linecount工具-CSDN博客
然后,讓ChatGPT幫我改為如下的完整代碼:
import os
from tkinter import Tk, Label, Button, filedialog
def open_file(file_path, encoding):
? ? try:
? ? ? ? file = open(file_path, 'r', encoding=encoding)
? ? ? ? return file
? ? except UnicodeDecodeError:
? ? ? ? return None
def count_lines_in_file(file_path, encodings=('gb2312', 'gbk', 'utf-8')):
? ? count = 0
? ? file = None
? ? for encoding in encodings:
? ? ? ? file = open_file(file_path, encoding)
? ? ? ? if file:
? ? ? ? ? ? break
? ? if not file:
? ? ? ? raise Exception(f'Error reading file: {file_path}')
? ? with file:
? ? ? ? for line in file:
? ? ? ? ? ? line = line.strip() ?# 剔除行首行尾的空白字符
? ? ? ? ? ? if line and not line.isspace() and not line.startswith('//'):
? ? ? ? ? ? ? ? # 如果不是空行、制表符行或注釋行,則計數器加1
? ? ? ? ? ? ? ? count += 1
? ?
? ? return count
def count_lines_in_directory(directory):
? ? total_count = 0
? ? for dirpath, dirnames, filenames in os.walk(directory):
? ? ? ? for filename in filenames:
? ? ? ? ? ? if filename.endswith('.c'):
? ? ? ? ? ? ? ? # 僅處理C源代碼文件
? ? ? ? ? ? ? ? file_path = os.path.join(dirpath, filename)
? ? ? ? ? ? ? ? try:
? ? ? ? ? ? ? ? ? ? count = count_lines_in_file(file_path)
? ? ? ? ? ? ? ? ? ? print(f'{file_path}: {count}')
? ? ? ? ? ? ? ? ? ? total_count += count
? ? ? ? ? ? ? ? except Exception as e:
? ? ? ? ? ? ? ? ? ? print(str(e))
? ? return total_count
?
windows = Tk()
windows.title("統計代碼行數小工具") ?#設置標題
windows.geometry("550x250")
def clicked(): ?#定義Button的事件處理函數
? ? directory = filedialog.askdirectory()
? ? L1.configure(text="C代碼文件總行數:%s 行\""
? ? ? ? ? ? ? ? ? ? ? %(count_lines_in_directory(directory)))
? ?
button = Button(windows,text="選擇文件夾并提交",command=clicked) ?#定義“提交”按鈕,并指定Button的事件處理函數
button.pack()
L1 = Label(windows,text = "",bg='white',width=200,height=10) ? ?#創建一個標簽,用于展示統計的代碼行信息
L1.pack()
windows.mainloop()
特點:支持三種編碼格式,你可以繼續加其它編碼。簡單直接 :)