您的位置:首页 > 编程语言 > Python开发

Python学习笔记——有用的module

2014-10-11 15:46 344 查看
1.Webbrowser:可以使用webbrowser控制浏览器(如果浏览器处于关闭状态,会触发打开浏览器)打开一个网页

import webbrowser

webbrowser.open('http://www.python.org')


2.Shelve:提供了一种更加简化的使用文件来存储数据的操作方法,即open文件->使用字符串作为键来创建或者读取记录->close文件的,一种类似DB或者dic的数据存储方式。相当于一种轻量级的文件数据库,并且简化了直接使用文件操作来存储数据中需要操作行,split行中的键、值等各种文件和字符串操作

import shelve

def store_person(db):

pid = raw_input('Enter unique ID number:')
person = {}
person['name'] = raw_input("Enter name:")
person['age'] = raw_input("Enter age:")
person['phone'] = raw_input("Enter phone number:")
db[pid] = person

def lookup_person(db):
pid = raw_input("Enter ID number:")
field = raw_input("what would you like to know?(name, age, phone)")
#先去除首尾的空格,再转化为小写
field = field.strip().lower()
#首字母大写
print field.capitalize() + ':', db[pid][field]

def print_help():
print "The available commands are:"
print "store   :Stores information about a person"
print "lookup  :Looks up a person from ID number"
print "quit    :Save changes and exit"
print "?       :Prints this message"

def enter_command():
#带命令提示
cmd = raw_input("Enter command(? for help):")
cmd = cmd.strip().lower()
return cmd

def main():
database = shelve.open('f:\\database.dat')
try:
while True:
#标准的提取命令行输入并解析的方式
cmd = enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == "?":
print_help()
elif cmd == "quit":
return
finally:
database.close()

if __name__=="__main__":
main()


3.Random:与随机数相关的module

import random

#返回0<=n<1之间的随机实数
print random.random()
#返回a<=n<b之间的随机实数
print random.uniform(10,20)

a = [1,2,3,4,5,6]
print random.choice(a)


执行结果:

0.713273128481

12.2090570538

6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: