最近读完了简明Python教程(A Byte of Python),在此书的最后作者建议读者实现一个命令行Python程序:

“在这个程序中,你可以添加、修改、删除和搜索你的联系人(朋友、家人和同事等等)以及它们的信息(诸如电子邮件地址和/或电话号码)。这些详细信息应该被保存下来以便以后提取。

现在特地来交作业,同时对作者Swaroop, C. H.和译者沈洁元表示感谢!谢谢两位无私的奉献:)

操作系统windows7,Python版本2.7.5。

#address.py

#首先我们需要一个字典用于存放联系人和他的地址信息,这份信息在硬盘上的保存方式为address.txt: 
address = {}
ff = open("address.txt")

#接下来是读取这个文本中的内容并存入字典中:

while True:
     line = ff.readline()     #逐行读取数据
     if len(line) == 0:
          break
     if line == "\n":
          continue
     address[line.split(",")[0]]=line.split(",")[1]     #添加文件内联系人数据至字典中
ff.close()                         #关闭

#实现添加方法:

def addUser():
     n = raw_input('name:')
     m = raw_input('address:')
     address[n]=m                                   #写入字典
     fileAdd = open("address.txt","a")     #追加写入文件
     fileAdd.write(n+","+m+"\n")
     fileAdd.close()

#实现修改方法:

def modify():
     n = raw_input('name:')          #获取待修改的用户名
     if n in address:
          m = raw_input('address:')     #获取修改后的地址
          address[n]=m                         #修改字典并写入文件
          fileModify = open("address.txt","w")
          for n,m in address.items():
               fileModify.write(n+","+m+"\n")
          fileModify.close()
     else:
          print 'cai wu ci ren'

#实现删除方法:

def delUser():
     n = raw_input('name:')                    #获取输入的联系人
     if n == "":
          return
     del address[n]                                   #从字典中删除此联系人
     fileDel = open("address.txt","w")     #将字典中的联系人重新写入文件
     for n,m in address.items():               
          fileDel.write(n+","+m+"\n")
     fileDel.close()

#实现查询方法:

def query():
     n = raw_input('name:')          #获取输入的联系人
     if n in address:
          print n,address[n]              #打印联系人信息
     else:
          print 'cai wu ci ren'

#最后添加命令入口:

flag= True     #如果没有退出命令则一直接收命令行输入的命令
while flag:
     n = raw_input('operate:')     #获取输入命令并调用相应方法
     if n=="add":
          addUser()
     if n =="delete":
          delUser()
     if n == "query":
          query()
     if n == "modify":
          modify()
     if n == "show":
          print address
     if n=="Q":                   #退出执行
          flag =False    
else:
     os.system('pause')     #注意,Linux下无此方法
 
另外附上一个比较粗糙的Java实现:
package com.lyon.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Address
{
  static Map<String, String> addressMap = new HashMap<String, String>();

  public static void main(String[] args)
  {
    File file = new File("C:\\pyTest\\address.txt");
    BufferedReader reader = null;
    try
    {
      reader = new BufferedReader(new FileReader(file));
      String tempString = null;

      while ((tempString = reader.readLine()) != null)
      {
        if (tempString.length() > 1)
        {
          String ss[] = tempString.split(",");
          addressMap.put(ss[0], ss[1]);
        }
      }
      reader.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    String s = readInput();
    if (s == "Q")
    {
      System.out.println("tuichu");
      return;
    }
  }

  public static String readInput()
  {
    while (true)
    {
      System.out.println("Operate:");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String path = new String();
      try
      {
        path = br.readLine();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
      if (path.equals("add"))
      {
        add();
      }
      else if (path.equals("delete"))
      {
        delete();
      }
      else if (path.equals("query"))
      {
        query();
      }
      else if (path.equals("modify"))
      {
        modify();
      }
      else if (path.equals("Q"))
      {
        return "Q";
      }
      else if (path.equals("show"))
      {
        System.out.println(addressMap);
      }
      else
      {
        System.out.println("input show,add,query,modify,delete or Q.");
      }
    }
  }

  @SuppressWarnings("rawtypes")
  private static void modify()
  {
    System.out.println("Name:");
    BufferedReader brName = new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    try
    {
      name = brName.readLine();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    Iterator iter = addressMap.entrySet().iterator();
    while (iter.hasNext())
    {
      Map.Entry entry = (Map.Entry) iter.next();
      Object key = entry.getKey();
      if (key.equals(name))
      {
        System.out.println("Address:");
        BufferedReader brAddress = new BufferedReader(new InputStreamReader(System.in));
        String address = new String();
        try
        {
          address = brAddress.readLine();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
        addressMap.put(name, address);
      }
    }
    try
    {
      FileWriter writer = new FileWriter("C:\\pyTest\\address.txt");
      Iterator ite = addressMap.entrySet().iterator();
      while (ite.hasNext())
      {
        Map.Entry entry = (Map.Entry) ite.next();
        Object key = entry.getKey();
        Object val = entry.getValue();
        writer.write(key + "," + val+ "\n");
      }
      writer.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  @SuppressWarnings("rawtypes")
  private static void query()
  {
    System.out.println("Name:");
    BufferedReader brName = new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    try
    {
      name = brName.readLine();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    Iterator iter = addressMap.entrySet().iterator();
    while (iter.hasNext())
    {
      Map.Entry entry = (Map.Entry) iter.next();
      Object key = entry.getKey();
      if (key.equals(name))
      {
        System.out.println(entry.getValue());
      }
    }
  }

  @SuppressWarnings("rawtypes")
  private static void delete()
  {
    System.out.println("Name:");
    BufferedReader brName = new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    try
    {
      name = brName.readLine();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    addressMap.remove(name);
    try
    {
      FileWriter writer = new FileWriter("C:\\pyTest\\address.txt");
      Iterator iter = addressMap.entrySet().iterator();
      while (iter.hasNext())
      {
        Map.Entry entry = (Map.Entry) iter.next();
        Object key = entry.getKey();
        Object val = entry.getValue();
        writer.write(key + "," + val+ "\n");
      }
      writer.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  private static void add()
  {
    System.out.println("Name:");
    BufferedReader brName = new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    try
    {
      name = brName.readLine();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    System.out.println("Address:");
    BufferedReader brAddress = new BufferedReader(new InputStreamReader(System.in));
    String address = new String();
    try
    {
      address = brAddress.readLine();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    addressMap.put(name, address);
    try
    {
      FileWriter writer = new FileWriter("C:\\pyTest\\address.txt", true);
      writer.write(name + "," + address + "\n");
      writer.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

posted on 2014-04-29 12:35  王敏慎  阅读(251)  评论(0编辑  收藏  举报