import argparse
import os
defcount_words(filename,min_len=0,ignore_case=False):
ifnotos.path.exists(filename):
returnf"错误:文件 {filename} 不存在"
withopen(filename,encoding="utf-8")asf:
words=f.read().split()
ifignore_case:
words=[w.lower()forwinwords]
ifmin_len>0:
words=[wforwinwordsiflen(w)>=min_len]
returnlen(words)
parser=argparse.ArgumentParser(description="统计文本文件中的单词数量")
parser.add_argument("file",help="要统计的文件路径")
parser.add_argument("-m","--min-len",type=int,default=0,help="单词最小长度")
parser.add_argument("-i","--ignore-case",action="store_true",help="忽略大小写")
args=parser.parse_args()
result=count_words(args.file,args.min_len,args.ignore_case)
print(result)