使用 python 实现 wc 命令程序的基本功能

简介: 这里使用了 python 的基本代码实现了 Linux 系统下 wc 命令程序的基本功能。   #!/usr/bin/env python #encoding: utf-8 # Author: liwei # Function: wc program by python from...

这里使用了 python 的基本代码实现了 Linux 系统下 wc 命令程序的基本功能。

 

#!/usr/bin/env python
#encoding: utf-8
# Author: liwei
# Function: wc program by python

from optparse import OptionParser
import sys,os

def opt():
    parser = OptionParser()
    parser.add_option('-c', '--char',
                      dest='chars',
                      action='store_true',
                      default=False, 
                      help='only count chars')

    parser.add_option('-w', '--word',
                      dest='words',
                      action='store_true',
                      default=False, 
                      help='only count words')

    parser.add_option('-l', '--line',
                      dest='lines',
                      action='store_true',
                      default=False, 
                      help='only count lines')
    
    parser.add_option('-n', '--nototal',
                      dest='nototal',
                      action='store_true',
                      default=False, 
                      help='don\'t print total information')

    options, args = parser.parse_args()
    return options, args

#print options
def get_count(data):
    chars = len(data)
    words = len(data.split())
    lines = data.count('\n')
    return lines, words, chars

#if not options.chars and not options.words and not options

def print_wc(options, lines, words, chars, fn):
    if options.lines:
        print lines,
    if options.words:
        print words,
    if options.chars:
        print chars,
    print fn

def main():
    options, args = opt()
    
    if not (options.lines or options.words or options.chars):
        options.lines, options.words, options.chars = True, True, True
    
    
    if args:
        total_lines, total_words, total_chars = 0, 0, 0
        for fn in args:
            if os.path.isfile(fn):
                with open(fn) as fd:
                    data = fd.read()
                lines, words, chars = get_count(data)
                print_wc(options, lines, words, chars, fn)
                total_lines += lines
                total_words += words
                total_chars += chars
            elif os.path.isdir(fn):
                print >> sys.stderr, '%s is a directory' %fn
            else:
                sys.stderr.write('%s: No such file or directory\n' % fn)
        # 只有多个文件的时候会计算出total字段
        if len(args) > 1 and not options.nototal:
            print_wc(options, total_lines, total_words, total_chars, 'total')
    else:
        fn = ''
        data = sys.stdin.read()
        lines, words, chars = get_count(data)
        print_wc(options, lines, words, chars, fn)
    
if __name__ == '__main__':
    main()

  

相关文章
|
1月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
239 101
|
1月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
171 99
|
1月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
153 98
|
1月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
2月前
|
人工智能 Linux 开发工具
Python从零到一:手把手带你写出第一个实用程序
Python语法简洁易懂,适合编程新手入门。它广泛应用于人工智能、自动化办公、Web开发等领域。学习Python可快速搭建项目,拥有丰富库支持和强大社区资源。通过本教程,你将掌握基础语法、环境搭建、程序逻辑控制及实战项目开发,开启编程之旅。
263 0
|
20天前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(一):认识Python、Py解释器作用;编写第一个Python程序;Python中的基本数据结构
认识Python 前提安装好Python,这里使用3.13版本 如今Python作为变成姐最炙手可热的编程语言,它的使用途径涵盖绝大部分生活中需要的开发需要。 许多大型网站就是用Python开发的,例如YouTube、Instagram,还有国内的豆瓣。很多大公司,包括Google、Yahoo等,甚至NASA都大量地使用Python。
303 1
|
1月前
|
设计模式 决策智能 Python
Python条件控制:让程序学会"思考"的魔法
本文深入浅出地讲解Python条件控制,从基础if语句到多分支、嵌套结构,再到简洁的三元表达式与Python 3.10新增的match-case模式匹配,结合电商折扣、会员等级、ATM系统等实战案例,全面掌握程序“智能决策”的核心逻辑。
245 0
|
4月前
|
PyTorch 算法框架/工具 C++
人工智能算法python程序运行环境安装步骤整理
本教程详细介绍Python与AI开发环境的配置步骤,涵盖软件下载、VS2017安装、Anaconda配置、PyCharm设置及组件安装等内容,适用于Windows系统,助你快速搭建开发环境。
|
5月前
|
人工智能 并行计算 开发者
CUDA重大更新:原生Python可直接编写高性能GPU程序
NVIDIA在2025年GTC大会上宣布CUDA并行计算平台正式支持原生Python编程,消除了Python开发者进入GPU加速领域的技术壁垒。这一突破通过重新设计CUDA开发模型,引入CUDA Core、cuPyNumeric、NVMath Python等核心组件,实现了Python与GPU加速的深度集成。开发者可直接用Python语法进行高性能并行计算,显著降低门槛,扩展CUDA生态,推动人工智能、科学计算等领域创新。此更新标志着CUDA向更包容的语言生态系统转型,未来还将支持Rust、Julia等语言。
411 3
CUDA重大更新:原生Python可直接编写高性能GPU程序
|
4月前
|
机器学习/深度学习 前端开发 API
python3如何使用QT编写基础的对话框程序
Qt与Python结合形成了PyQt/PySide,为桌面应用开发提供强大支持。通过简单安装PyQt5或PySide6,开发者可快速搭建跨平台GUI应用。本文从创建基础对话框入手,介绍布局管理、信号与槽机制、对话框模式及样式表美化等核心功能,并探讨模态窗口、事件驱动编程和资源打包等内容。最后,引导读者探索模型视图架构、多线程处理等进阶技术,逐步掌握用Python+Qt开发高效桌面应用的技能。
153 0

推荐镜像

更多