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

学习python(4) 练习词典功能 查询增加删除更新

2014-04-24 17:38 579 查看
#-*-coding:utf-8 -*-
"""
dtc
查询单词功能
增加单词功能
删除单词功能
更新单词功能
文件内容如下:
P0009 Engine Position System Performance Bank 2		
P000A A Camshaft Position Slow Response Bank 1		
P000B B Camshaft Position Slow Response Bank 1		
P000C A Camshaft Position Slow Response Bank 2		
P000D B Camshaft Position Slow Response Bank 2		
"""
import os

def search():

	w = raw_input("search word : ")
	dic = {}
	f = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'r')
	lines = f.readlines()
	search_success = 0
	for line in lines:
		key = line[:5]
		comment = line[6:]
		dic[key] = comment
		if w in dic.keys():
			search_success = 1
			print "word\tmean\n"
			print w,dic[w],
			print "========查询完毕=============="
			f.close()
			break
	if search_success ==0:
		print "Not found~!"
				

def add():

	while 1:
		w = raw_input("add word : ")
		dic = {}
		f = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'r')
		lines = f.readlines()
		search_success = 0
		for line in lines:
			key = line[:5]
			comment = line[6:]
			dic[key] = comment
			if w in dic.keys():
				search_success = 1
				f.close()
				break
		if search_success ==1:
			print"该单词已经存在,重新添加~"
		else:
			f.close()
			break
	mean = raw_input("this word mean : ")
	f1 = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'a')
	f1.write(w+' '+ mean + '\n')
	print"=========添加成功============="
	f1.close()
		
	
def delete():

	w = int(raw_input("delete 哪一行数 : "))
	i =1
	f = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'r')
	temp = open("/Python_Data/work/temp.txt",'w')
	while 1:
		line = f.readline()
		if line:
			if i == w:
				i = i +1
				print "找到第%d: %s"%(w,line)
				continue
			else:
				i = i +1
				writeline = '%s'% line
				temp.write(writeline)
		else:
			print "文件已到末尾"
			break
	f.close()
	temp.close()
	os.remove("/Python_Data/work/123_OBDII_dtc_en_2.txt")
	os.rename("/Python_Data/work/temp.txt","/Python_Data/work/123_OBDII_dtc_en_2.txt")
	print "============删除成功===============!"
	
def update():

	w = int(raw_input("update 哪一行数 : "))
	f = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'r+')
	lines = f.readlines()
	mean = raw_input("new mean:")
	lines[w] = mean	+ "\n"
	f = open("/Python_Data/work/123_OBDII_dtc_en_2.txt",'w+')
	f.writelines(lines)
	print "========更新完毕=============="
	f.close()

def main():

	while 1:
		print "||=================||\n"
		print "||请选择下面功能...||\n"
		print "|| a 查询单词功能  ||\n"
		print "|| b 增加单词功能  ||\n"
		print "|| c 删除单词功能  ||\n"
		print "|| d 更新单词功能  ||\n"
		print "|| e 退出单词功能  ||\n"
		print "||=================||\n"
		i = raw_input("选中 : ")
		
		if i == 'a'or i == 'A':
			search()
		elif i == 'b' or  i =='B':
			add()
		elif i == 'c' or i =='C':
			delete()
		elif i == 'd' or i == 'D':
			update()
		elif i =='e' or i =='E':
			exit()

if __name__== '__main__':
	main()


下面学习开源网上的版本:对比一下差距



# -*- coding: cp936 -*-
import os 

# 读取数据 
fname = 'myphonebookdata' 
if fname in os.listdir('.'): 
    data = {line.strip().split('~')[0]:line.strip().split('~')[1] for line in open(fname,'r').readlines()} 
else: 
    data = {} 
#主循环 
ask = raw_input('欢迎使用电话本:-) 添加(A)/查找(S)/删除(D)/退出(<ENTER>)? ').strip().lower() 
while len(ask)>0: 
    if ask=='a': 
        print '开始添加...' 
        name = raw_input('名字: ').strip() 
        while name in data: 
            print '名字已经存在,请重新输入...' 
            name = raw_input('名字: ').strip() 
        number=raw_input('电话号码: ').strip() 
        while len(number)==0: 
            print '空电话号码,请重新输入...' 
            number=raw_input('电话号码: ').strip() 
        data[name] = number 
        print '添加成功!' 
    elif ask=='s': 
        print '开始查找...' 
        name = raw_input('名字: ').strip() 
        if name in data: 
            print '名字\t\t电话号码' 
            print '%s\t\t%s' % (name,data[name]) 
            print '查找完成!' 
        else: 
            print '找不到!' 
    elif ask=='d': 
        print '开始删除...' 
        name = raw_input('名字: ').strip() 
        if name in data: 
            del data[name] 
            print '删除成功!' 
        else: 
            print '没有要删除的名字!' 
    else: 
        print '未定义操作,请重新输入' 
    print 
    ask = raw_input('欢迎使用电话本:-) 添加(A)/查找(S)/删除(D)/退出(<ENTER>)? ').strip().lower() 
# 写入数据 
s = '' 
for k in data: 
    s += '%s~%s\n' % (k,data[k]) 
fout = open(fname,'w') 
fout.write(s) 
fout.close()



够简洁,最后才对文件写操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐