2011-07-09 33 views
-1

嗨,我有我的customer.txt文件列表打印出整個客戶信息:我在我的customer.txt列表如何創建一個搜索功能使用python

[1, 'Amin Milani Fard', 'Columbia College', 778] 
[33, 'Ali Sulemanji', 'Langara College', 4324442211] 
[32, 'Ali Sulemanji', 'Langara College', 4324442211] 
[325, 'Ali Sulemanji', 'Langara College', 4324442211] 
[2, 'Yuvin Ng','Dougles College',77839922003] 
[3, 'Ali Sulemanji', 'Langara College', 4324442211] 

我的工作就是創建一個可以跟蹤客戶名稱的搜索功能。 爲如。 輸入客戶名稱:Yuvin Ng 它將返回Yuvin Ng的整個列表

我該怎麼做?使用python。

def search(n): 
    name=input('Customer Name:') 
    x=open('customerlist.txt','r') 
    i=0 
    while i<1000: # anyway this is out of desperation to make the function work... 
     z=x.readline() 
     print(z) 
     i+=1 

IM卡... pleease幫助儘快THX你..

回答

3

一個簡單的方法是遍歷使用in,檢查是否有匹配的文件中的行,如果發現匹配使用eval將該行作爲列表返回。

def search(file_name, name): 
    with open(file_name) as f: 
     for line in f: 
      if name in line: 
       return eval(line) 
    return [] 

>>> search('customer.txt', 'Yuvin Ng') 
<<< [2, 'Yuvin Ng', 'Dougles College', 77839922003] 
+1

...但只有當'customer.txt'來自可信來源? –

+0

它的工作! thx .....但在我的Python班,我還沒有學習和as或eval() 我期望你使用while循環和List []出來與搜索功能。 –

+0

你可以解析這行而不是使用eval,它不是太多額外的工作,只是去掉括號,分開逗號等等。 – zeekay

-1

爲什麼不使用數據庫而不是平面文件來存儲信息?例如,如果你想使用一個名爲「用戶」的數據庫,你可以有像

import _mysql 
conn = _mysql.connect('localhost','root','','users') 
with open(filename) as fp: 
    for line in fp: 
     then fill your query with the information like: 
     "..." % dict(zip([id,name,college,number],eval(line))) 

將來的查詢然後可以像

def search(name): 
    cursor = conn.cursor() 
    cursor.execute("Select * from users.users where name = %(name)"%locals()) 
    data = cursor.fetchone() 
    cursor.close() 
    return data 
0

做過認爲你必須看看pickle module 。您的代碼比看起來會看起來如下:

data = [[1, 'Amin Milani Fard', 'Columbia College', 778], 
[33, 'Ali Sulemanji', 'Langara College', 4324442211], 
[32, 'Ali Sulemanji', 'Langara College', 4324442211], 
[325, 'Ali Sulemanji', 'Langara College', 4324442211], 
[2, 'Yuvin Ng','Dougles College',77839922003], 
[3, 'Ali Sulemanji', 'Langara College', 4324442211]] 

import pickle 

pickle.dump(data, open('c:\\file.txt','w')) 

# than you can retrieve data the following way 

data = pickle.load(open('c:\\file.txt','r')) 

# And now it is very easy to find data you need. 
data[1] 
>>> [33, 'Ali Sulemanji', 'Langara College', 4324442211] 

# OR 
for x in data: 
    if 'Ali Sulemanji' in x:# or look for any other property/ies 
     print x 
相關問題