# 第二次作业 **Repository Path**: stickybird/second-assignment ## Basic Information - **Project Name**: 第二次作业 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-10-28 - **Last Updated**: 2024-10-29 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 第二次作业 #### 介绍 第二次的作业实现了基础功能外 这个程序还将提供简单的命令行接口,用户可以通过不同的参数来统计文本文件中的字符数、单词数、句子数等信息。扩展功能将允许统计代码行、空行和注释行。 命令行用法示例: > wc.exe -c file.txt # 统计字符数 > wc.exe -w file.txt # 统计单词数 > wc.exe -s file.txt # 统计句子数 > wc.exe -l file.txt # 统计代码行数 > wc.exe -e file.txt # 统计空行数 > wc.exe -cmt file.txt # 统计注释行数 #### 软件架构 > import sys > import re > > def count_characters(filename): > with open(filename, 'r') as file: > text = file.read() > return len(text) > > def count_words(filename): > with open(filename, 'r') as file: > text = file.read() > return len(re.findall(r'\b\w+\b', text)) > > def count_sentences(filename): > with open(filename, 'r') as file: > text = file.read() > return len(re.findall(r'[.!?]+', text)) > > def count_lines(filename): > with open(filename, 'r') as file: > return sum(1 for line in file if line.strip()) > > def count_empty_lines(filename): > with open(filename, 'r') as file: > return sum(1 for line in file if not line.strip()) > > def count_comment_lines(filename): > with open(filename, 'r') as file: > return sum(1 for line in file if line.strip().startswith('#')) > > def main(): > if len(sys.argv) != 3: > print("Usage: wc.exe [option] [filename]") > sys.exit(1) > > option = sys.argv[1] > filename = sys.argv[2] > > if option == '-c': > print(count_characters(filename)) > elif option == '-w': > print(count_words(filename)) > elif option == '-s': > print(count_sentences(filename)) > elif option == '-l': > print(count_lines(filename)) > elif option == '-e': > print(count_empty_lines(filename)) > elif option == '-cmt': > print(count_comment_lines(filename)) > else: > print("Invalid option") > > if __name__ == "__main__": > main() > > #### 使用教程 通过win+R调出命令行窗口输出cmd,进入终端。 进入到代码所在的路径。 按照如下指令运行程序。 **基础命令** wc.exe -c file1.txt 统计字符数。 wc.exe -w file2.txt 统计单词数。 wc.exe -s file1.txt 统计句子数。 **注:file1,file2是测试的文件,可以自行更改。** **拓展命令** wc.exe -l file1.txt 统计代码行。 wc.exe -e file2.txt 统计空行。 wc.exe -m file1.txt 统计注释行。 #### 简单测试 在命令栏目输入以下代码 经过验证,代码正确 ![输入图片说明](%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-28%20194303.png)