首先是白嫖以下大神的代码:统计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()
特点:支持三种编码格式,你可以继续加其它编码。简单直接 :)