模块的使用
-
模块是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