2017-04-24 30 views
-1

我將解釋我的代碼項目驗證,並設置格式化

  1. 您輸入文件名稱和項目名稱的行爲。

  2. 它會在列表中顯示物料的名稱和數量。

第一個問題:其實,我想讓它顯示列表中的第二項,並告訴它是重複的。目前,如果我刪除列表(集(),我將分別獲得2個香蕉輸出相同的字符串。.txt文件的

例如我進口。的

bananes: 18 
pommes: 23 
bananes: 13 

例子txt文件我進口輸入的

pommes : 54 
: 18 
banane: 

oranges : 30 

例如:

item.py data10.txt bananes 
需要輸出的

例如:

La ligne banane : 13 est un doublon. 

輸出我得到:

La ligne ['1', 's', ' ', 'e', ',', "'", '8', 'n', ':', 'b', '2', 'a'] est un doublon. 

問題二:如果我寫的任何其它的字比是在列表中的單詞也能正常工作。但實際上,如果我寫出單詞的幾個首字母,它仍然會完全顯示該行。輸入

例如:

pomm: 0 

輸出我得到:需要輸出的

item.py data10.txt pomm 

例如

pomme: 30 

這裏是我的代碼,這樣你可以有一個想法是什麼我這樣做:

import sys 

def ligne(texte): 
    try: 
     with open(texte) as ouvrir: 
      lecture = ouvrir.readlines() 
      words = [" : ".join([x.strip() for x in line.split(":")]) for line in lecture] 
      words = [x for x in words if len(x) > 1] 
      return words 
    except IOError: 
     print("Le fichier", texte, "n'existe pas.") 
     sys.exit() 

def recherche(essaie): 
    while True: 
     if len(essaie) > 3: 
      print("Deux arguments sont attendus, le nom du fichier d'inventaire et l'item") 
      sys.exit() 
     elif len(essaie) < 3: 
      print("Il faut préciser le nom du fichier et de l'item.") 
      sys.exit() 
     else: 
      entree = essaie[1] 
      item = essaie[2] 
      choix = str(entree) 
      texte = choix.strip("[']") 
      resultat = [s for s in ligne(texte) if item in s] 
      resultat2 = str(resultat) 
      longueur = len(resultat) 
      resultat3 = resultat2.strip("[']") 
      resultat4 = list(set(resultat3)) 
      if item in str(ligne(texte)): 
       if longueur > 1: 
        print("La ligne", resultat4, "est un doublon.") 
        sys.exit() 
       else: 
        print(resultat3) 
        sys.exit() 
      else: 
       print(item, ": 0") 
       sys.exit() 

if __name__ == "__main__": 
    recherche(sys.argv) 
+0

我已經嘗試了很多事情來嘗試解決這些問題而沒有成功 –

+1

str(ligne(texte))中的item中的每個項目都是由'ligne()返回的列表表示的單個字符。 ',這不是你想要的。 'resultat4 = list(set(resultat3))'有一個類似的問題,因爲'resultat3'是一個字符串,所以從中創建一個集合會導致字符串中的字符集合,然後將其轉換爲您所在的列表看到被打印出來。我想重要的一點是,在Python中,字符串是序列,是可迭代的,因此可以與列表混淆。 – martineau

+0

我不知道如何將您的建議應用於我的代碼我很抱歉 –

回答

2

您可能需要考慮使用字典來解決這個問題,而不是使用字符串的列表/字符集。您可以將行讀作鍵/值對,然後檢查密鑰是否已存在於字典中。如果是這樣,這是一個重複,並拋出一個異常(如果你喜歡,你可以代替這對於印刷字符串和sys.exit(0)。

檢查下面的示例代碼...

import sys 

def ligne(texte, item): 
    try: 
     with open(texte) as ouvrir: 
      words_dict = {} #Create new, empty dictionary 
      lecture = ouvrir.readlines() 
      for line in lecture: #For each line in .txt file 
       line = line.strip('\n') 
       key, number = line.split(':')[0], int(line.split(':')[1]) #Item is before ':', value is after 
       if key not in words_dict.keys(): 
        words_dict[key] = number #If that item isn't in the dictionary yet (this is the first occurence), add it 
       elif key == item: #If the duplicate is the inputed item 
        raise Exception('La ligne {} est un doublon.'.format(line)) #If that item is already in the dictionary, raise an exception 
      return words_dict #If there are no duplicates, the dictionary will be returned, if there are, it will return the error above 
    except IOError: 
     print("Le fichier", texte, "n'existe pas.") 
     sys.exit() 

def recherche(essaie): 
    if len(essaie) > 3: 
     print("Deux arguments sont attendus, le nom du fichier d'inventaire et l'item") 
     sys.exit() 
    elif len(essaie) < 3: 
     print("Il faut preciser le nom du fichier et de l'item.") 
     sys.exit() 
    else: 
     entree = essaie[1] 
     item = essaie[2] 

     choix = str(entree) 
     texte = choix.strip("[']") 
     resultat_dict = ligne(texte, item) #If this returns without raising an exception, there were no duplicates 

     if item in resultat_dict.keys(): 
      print item, ": {}".format(resultat_dict[item]) #If the item was in the .txt file, print it and its value 
     else: 
      print item, ": 0" #If not, print with a value of zero 

if __name__ == "__main__": 
    recherche(sys.argv) 

我試着留下評論來解釋所有的變化,但是讓我知道是否有什麼不清楚的地方。關鍵的變化是將文件讀入字典並在發現重複時引發異常,但是我儘可能地做到了保持原始代碼的結構不變(儘管可能有更簡單的方法/更有效的方法來解決這個問題)。recherche函數的最後一部分也變得更簡單了,因爲你知道如果ligne沒有錯誤返回,就沒有重複。

+0

程序輸出someting如果有重複,但它不工作就像我提到的問題。如果我輸入單詞pommes作爲例子,它也不起作用,即使它在列表中它也會輸出0。嘗試一個不包含重複的列表。我正在研究你的答案,並試圖找出答案。如果你有任何隊列,它會有所幫助! –

+0

嗯,你使用的.txt文件是什麼?它是以'pommes'作爲輸入的結果,當你嘗試它時它會返回什麼? – slearner

+0

我得到一個超出範圍的一些時間鍵,number = line.split(':')[0],int(line.split(':')[1]) IndexError:列表索引超出範圍和所有其他結果我得到,如果我嘗試與其他項目的其他文件都等於0,因爲我有文件,看起來像我剛剛在我的問題中添加 –