使用Python语言编写程序,要求该程序可以识别文件夹内的Python文件,并输出文件数量,总代码行数,总注释行数和空行数
时间: 2024-10-21 19:14:21 浏览: 17
你可以使用Python的os模块来遍历文件夹,结合ast模块统计代码行数,re模块处理字符串查找注释和空行。下面是一个简单的示例程序:
```python
import os
import ast
import re
def count_code_info(directory):
file_count = 0
total_lines = 0
comment_lines = 0
blank_lines = 0
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
# 判断是否为空行
blank_lines += len([line for line in code.split('\n') if line.strip() == ''])
# 计算总代码行数
total_lines += len(code.split('\n'))
# 使用正则表达式匹配单行或多行注释
comment_pattern = re.compile(r'(#[^\n]*\n?)|(\s*/\*.*?\*/)')
comment_lines += len(comment_pattern.findall(code))
file_count += 1
return file_count, total_lines - comment_lines - blank_lines, comment_lines, blank_lines
# 调用函数并输出结果
directory_path = '/path/to/your/directory'
file_count, code_lines, comment_lines, blank_lines = count_code_info(directory_path)
print(f"文件总数: {file_count}")
print(f"总代码行数: {code_lines}")
print(f"总注释行数: {comment_lines}")
print(f"空行数: {blank_lines}")
阅读全文