2017-01-07 23 views
0

我有一個代碼嘗試更改文本文件中列表中的某個項目。該文本文件包含電子郵件,每行的密碼類似於登錄系統。 代碼要求用戶輸入電子郵件,然後二進制文件在文本文件的列表中搜索該用戶。如果用戶在場,那麼我想要更改該用戶的密碼,以便在列表中追加[1]項目。 這裏是我的更改密碼到目前爲止更改文本文件列表中的某個項目

def ChangePassword(): 

    while True: 
     email=input("Enter the email you want to change the password for") 
     res=BinarySearch(logindata,email) 
     if res: 
      break 

代碼,我知道它不是很多,但我還沒有一個線索如何做到這一點,我將如何處理這?
這是我的二進制搜索本身的代碼,如果需要的話。

def BubbleSort(logindata): 
    NoSwaps = 1 
    N = len(logindata) 
    logindata = list(logindata) 
    while NoSwaps == 1: 
     Count = 1 
     NoSwaps = 0 
     for Count in range(N-1): 
      if logindata[Count] > logindata[Count+1]: 
       temp = logindata[Count] 
       logindata[Count] = logindata[Count+1] 
       logindata[Count+1]=temp 
       NoSwaps=1 
    return tuple(logindata) 

def BinarySearch(logindata,email): 
    First=0 
    Last=len(logindata)-1 
    while First <= Last: 
     Midpoint = (First + Last) // 2 
     if logindata[Midpoint][0] == email: 
      print("Email Found") 
      return True 
     elif logindata[Midpoint][0] > email: 
      Last = Midpoint - 1 
     else: 
      First = Midpoint + 1 
    print("Not found") 
    return False 
+0

你確定該文件是排序?無論如何,python內置插件可能(至少)和你的實現一樣快。你爲什麼要再次執行搜索? – kabanus

+0

因爲我必須使用二進制搜索,所以即使效率不高,我也知道它很煩人,並且關於正在排序的文件,它應該按照字母順序排列的冒泡排序? @kabanus –

+0

所以要清楚,你讀了一個文件,對它進行冒泡排序,二進制查找電子郵件並更改項目,然後將結果寫入(新文件或原始文件)? – kabanus

回答

0

假如你實現你的排序和正確的搜索代碼(由你),並假設你的文件是一堆表格「電子郵件密碼」的行,你只是想:

def ChangePassword(loginfile): 
    with open(loginfile) as desc: 
     logindata = BubbleSort([line.split() for line in desc.readlines()]) 

    while True: 
     email=input("Enter the email you want to change the password for") 
     res=BinarySearch(logindata,email) 
     if res < 0: 
      break 
     else: print "Not found!" 

    pass = input("Enter new password: ") 
    while pass != input("Please verify: "): 
     pass = input('Mismatch! enter again: ') 

    logindata[1] = pass 
    with open(loginfile,'w') as desc: 
     desc.write("\n".join(" ".join(x) for x in logindata)) 

注意我希望BinarySearch返回相關行的索引,而不是密碼。 -1如果沒有找到。這是解決方案的一個非常基本的草圖,儘管它很有用,可以考慮尋找更快的解決方案!

相關問題