12-3

模块的使用

  • 模块是python组织代码的基本方式

  • 一个python脚本可以单独运行,也可以导入到另一个脚本中运行,当脚本被导入运行时,我们称其为模块

  • 所有的.py文件都可以作为一个模块导入

  • 编写统计字符,单词,行数

#!/bin/python

def wordCount(s):
    chars = len(s)
    words = len(s.split())
    lines = len(s.split('\n'))
    print(chars,words,lines)

with open('passwd','r') as fd:
    wordCount(fd.read())

[root@localhost studypy]# python3 12-3.py 
978 40 21

  • 导入这个模块
[root@localhost studypy]# vim 12-3-1.py
#!/bin/python

import word

[root@localhost studypy]# python3 !$
python3 12-3-1.py
978 40 21

  • 优化模块
#!/bin/python

def wordCount(s):
    chars = len(s)
    words = len(s.split())
    lines = len(s.split('\n'))
    print(chars,words,lines)

if __name__ == '__main__':
    with open('passwd','r') as fd:
        wordCount(fd.read())

[root@localhost studypy]# python3 12-3-1.py
18 3 2

  • ipython的调用方法
In [1]: from studypy import word

In [2]: word.wordCount('abc')
3 1 1

In [3]: from studypy.word import wordCount

In [4]: wordCount('abc')
3 1 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值