2016-06-30 11 views
-1

Ich möchte wissen, wie man die Gesamtsumme der Zahl aus einer Spalte in einer Textdatei in Python finden.Finden einer Summe von Zahlen aus einer Spalte in der Textdatei Python

Meine Datei:

123 Hammer 20 36 
124 Knife 10 10 
125 Rod  90 20 

Ich möchte die vierte Spalte in der Textdatei hinzuzufügen. Das ist die Spalte, die mit 36 ​​beginnt. Die Funktion sollte die Summe der Spalte zurückgeben, die 66 ist.

Ich habe noch keinen Code, wie ich immer noch in diesem Problem stecken und über eine Möglichkeit, es zu lösen denke .

Ich habe Fehler an einigen Stellen, ich denke, dass es aufgrund meines Codes ist. Ich brauche Hilfe darin.

# Creating class Hardware to store the linked list data in to the class, Properties like get and set 
class Hardware: 
    def __init__(self,barcode,description,price,quantity): # initating data 
     self.barcode=barcode 
     self.description=description 
     self.price=price 
     self.quantity=quantity 
     self.next=None 

    def getData(self):#function to get data 
     return self.barcode,self.description,self.price,self.quantity 

    def getNext(self):#function to get the next data 
     return self.next 

    def setData(self,newBarcode,newDescription,newPrice,newQuantity):#function to set the data 
     self.barcode=newBarcode 
     self.description=newDescription 
     self.price=newPrice 
     self.quantity=newQuantity 

    def setNext(self,newNext):#function to set the next data 
     self.next=newNext 

# LinkedList class for manipulation of data that is add, display and update 
class LinkedListHardware: 
    def __init__(self): # initating data 
     self.head=None 

    def isEmpty(self): #checks if the data is empty 
     return self.head==None 

    def ReadFile(self): # Reads a text file called Hardware 
     Hardwarefile=open('Hardware.txt','r') 
     return Hardwarefile.read() 

    def add(self,itemBarcode,itemDescription,itemPrice,itemQuantity): #Adds data to the linked list and also writes to the file 
     temp=Hardware(itemBarcode,itemDescription,itemPrice,itemQuantity) 
     temp.setNext(self.head) 
     self.head=temp 
     HardwareItems=(itemBarcode,itemDescription,itemPrice,itemQuantity) 
     Hardwarefile=open('Hardware.txt','a+') 
     Hardwarefile.write('\n') 
     for items in HardwareItems: 
      Hardwarefile.write(str(items)+'\t') 
     return "Added Successfully" 
     Hardwarefile.close() 


    def display(self,itemBarcode): # Displays a line based on the Barcode the user enters 
     current=self.head 
     with open('Hardware.txt','r') as f: 
      found=False 
      for line in f: 
       lines=line.split() 
       if itemBarcode in lines: 
        found=True 
        return line 
      if not found: 
       return "No such Barcode" 
      f.close()   

    def update(self,itemBarcode,itemDescription,itemPrice,itemQuantity): #update data of hardware item 
      current=self.head 
      with open('Hardware.txt','r+') as f: 
       found=False 
       for lines in f: 
        line=lines.split() 
        if itemBarcode not in line: 
         array=[] 
         array.append(line) 
         st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array] 
         st=''.join(st) 

         with open('Hardwareupdate.txt','a+') as outfile: 
          outfile.write('\n'+str(st)) 
          found=True 
         HardwareItems=(itemBarcode,itemDescription,itemPrice,itemQuantity) 
         Hardwarefile=open('Hardwareupdate.txt','a+') 
         Hardwarefile.write('\n') 
         for items in HardwareItems: 

          Hardwarefile.write(str(items)+'\t') 

       return "Added Successfully" 


      if not found: 
        return "No such Transaction" 



# Creating class Transaction to store the linked list data in to the class, Properties like get and set 
class Transaction: 
    def __init__(self,invoiceNumber,Barcode,totalPrice,Quantity): # initating data 
     self.invoiceNumber=invoiceNumber 
     self.Barcode=Barcode 
     self.totalPrice=totalPrice 
     self.Quantity=Quantity 

     self.next=None 

    def getData(self): #function to get data 
     return self.invoiceNumber,self.Barcode,self.totalPrice,self.Quantity 

    def getNext(self): #function to get the next data 
     return self.next 

    def setData(self,newinvoiceNumber,newBarcode,newtotalPrice,newQuantity): #function to set the data 
     self.invoiceNumber=newinvoiceNumber 
     self.Barcode=newBarcode 
     self.totalPrice=newtotalPrice 
     self.Quantity=newQuantity 


    def setNext(self,newNext): #function to set the next data 
     self.next=newNext 

# LinkedList class for manipulation of data that is add, search, update and delete 
class LinkedListTransaction: 

    # initating data 
    def __init__(self): 
     self.head=None 

    #checks if the data is empty 
    def isEmpty(self): 
     return self.head==None 

    #Adds data to the linked list and also writes to the file 
    def add(self,iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice): 
     temp=Transaction(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice) 
     temp.setNext(self.head) 
     self.head=temp 
     TransactionItems=(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice) 
     Transactionfile=open('Transaction.txt','a+') 
     Transactionfile.write('\n') 
     for items in TransactionItems: 
      if iteminvoiceNumber != ' ': 
       Transactionfile.write(str(items)+'\t') 
     return "Added Successfully" 

    # Displays the record of data by receving the item invoice number 
    def display(self,iteminvoiceNumber): 
      current=self.head 
      with open('Transaction.txt','r') as f: 
       found=False 
       for line in f: 
        lines=line.split() 
        if iteminvoiceNumber in lines: 
         found=True 
         return line 
       if not found: 
        return "No such Transaction" 

    # Removes sepcific data from the file (rewrites data that does not contain the data which user entered and writes to another file) 
    def remove(self,iteminvoiceNumber): 
     current=self.head 
     with open('Transaction.txt','r') as f: 
      found=False 
      for lines in f: 
       line=lines.split() 

       if iteminvoiceNumber not in line: 
        array=[] 
        array.append(line) 
        st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array] 
        st=''.join(st) 
        with open('Transactionlatest.txt','a+') as outfile: 
         outfile.write('\n'+str(st)) 
         found=True 

      if not found: 
        return "No such Transaction" 

    # Updates Data from the text file. Copies data to new file and then update whatever user enters 
    def update(self,iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice): 
      current=self.head 
      with open('Transaction.txt','r+') as f: 
       found=False 
       for lines in f: 
        line=lines.split() 
        if iteminvoiceNumber not in line: 
         array=[] 
         array.append(line) 
         st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array] 
         st=''.join(st) 

         with open('Transactionupdate.txt','a+') as outfile: 
          outfile.write('\n'+str(st)) 
          found=True 
         TransactionItems=(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice) 
         Transactionfile=open('Transactionupdate.txt','a+') 
         Transactionfile.write('\n') 
         for items in TransactionItems: 

          Transactionfile.write(str(items)+'\t') 

       return "Added Successfully" 


      if not found: 
        return "No such Transaction" 


    def TotalSales(self): 
     mysum=0 
     with open('Transaction.txt','r') as f: 
      for line in f: 
       mysum+=int(line.split()[3]) 
      return mysum 





HardwareList=LinkedListHardware() 

TransactionList=LinkedListTransaction() 
print(TransactionList.TotalSales()) 
print(TransactionList.remove(input())) 
''' 
print("Hardware Shop\n") 
print("[1]Update hardware item quantity in hand or price per unit\n") 
print("[2]Add hardware item\n") 
print("[3]Display hardware item\n") 
print("[4]Add Sales Transaction\n") 
print("[5]Remove Sales Transaction\n") 
print("[6]Edit Sales Transaction\n") 
print("[7]All Sales Transaction\n")   

MainInput=input("Enter Selection: ") 

HardwareList=LinkedListHardware() 

TransactionList=LinkedListTransaction() 


if MainInput=='1': 
    print("\nUpdate hardware item quantity in hand or price per unit") 
    print(HardwareList.update(input("Enter Barcode: "),input("Enter Description: "),input("Enter Price: "),input("Enter Quantity: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 


if MainInput=='2': 
    print("\nAdd hardware item") 
    print(HardwareList.add(input("Enter Barcode: "),input("Enter Description: "),input("Enter Price: "),input("Enter Quantity: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 

if MainInput=='3': 
    print("\nDisplay hardware item") 
    print(HardwareList.display(input("Enter Barcode: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 

if MainInput=='4': 
    print("\nAdd Sales Transaction") 
    print(TransactionList.add(input("Enter Invoice Number: "),input("Enter Hardware Barcode: "),input("Enter Quantity: "),input("Enter Total Price: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 

if MainInput=='5': 
    print("\nRemove Sales Transaction") 
    print(TransactionList.remove(input("Enter Invoice Number: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 

if MainInput=='6': 
    print("\nEdit Sales Transaction") 
    print(TransactionList.update(input("Enter Invoice Number: "),input("Enter Hardware Barcode: "),input("Enter Quantity: "),input("Enter Total Price: "))) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 

if MainInput=='7': 
    print("\nAll Sales Transaction") 
    print(TransactionList.TotalSales()) 
    SubInput=int(input("Enter 0 to exit and 1 to continue ")) 
    if SubInput==0: 
     quit() 
    if SubInput==1: 
     print("Hardware Shop\n") 
     print("[1]Update hardware item quantity in hand or price per unit\n") 
     print("[2]Add hardware item\n") 
     print("[3]Display hardware item\n") 
     print("[4]Add Sales Transaction\n") 
     print("[5]Remove Sales Transaction\n") 
     print("[6]Edit Sales Transaction\n") 
     print("[7]All Sales Transaction\n")   

     MainInput=input("Enter Selection: ") 



''' 

Der Fehler ist erhalten

mysum+=int(line.split()[3]) 
IndexError: list index out of range 
+1

werfen Sie einen Blick auf https://docs.python.org/3/tutorial/inputoutput.html#rea ding-and-writing-files und https://docs.python.org/3/library/stdtypes.html#str.split – Sundeep

+0

Lesen Sie es, aber immer noch unklar. Kannst du mir bitte ein Codebeispiel machen oder den Code machen? Vielen Dank. – Ahzam

+0

Ich denke, was Sie versuchen sollten, ist, die Datei Zeile für Zeile zu lesen, dann teilen Sie jede Zeile mit 'str.split' und erhalten Sie das vierte Element dh. 'split_line [3]' und füge das zu einer Variablen als Zahl hinzu (zB 'mysum + = int (split_line [3])' um die Summe zu erhalten. –

Antwort

0

Diese Arbeit sollte:

mysum = 0 
with open('myfilename','r') as f: 
    for line in f: 
     mysum += int(line.split()[3]) 

line.split()"123 Hammer 20 36" in ["123", "Hammer", "20", "36"] verwandeln wird. Wir nehmen den vierten Wert 36 mit dem Index [3]. Dies ist immer noch eine Zeichenfolge und kann unter Verwendung von int oder einer Dezimalzahl (Fließkommazahl) unter Verwendung von float in eine Ganzzahl konvertiert werden.

EDIT:

zu überprüfen, für leere Linien den Zustand if line: in der for-Schleife hinzuzufügen. In Ihrem Fall könnte tun Sie so etwas wie:

for line in f: 
    words = line.split() 
    if len(words)>3: 
     mysum += int(words[3]) 
+0

Noch bekomme ich den gleichen Fehler – Ahzam

+0

Ich versuchte dies auf eine andere Datei, die es funktioniert.Wenn ich zuvor dieses verwendet habe, habe ich es in einer Funktion in einer Klasse verwendet und die zurückgerufen.Wenn ich es anrufe gibt es mir den Fehler. Mein Code, um die Funktion aufzurufen TransactionList = LinkedListTransaction() Drucken (TransactionList.TotalSales()) – Ahzam

+0

@Ahzam Ich kann Ihnen nicht mit einem Fehler in einer Klasse oder Funktion helfen, die Sie nicht vorgestellt haben –

0

Dies ist Python, der eine Datei öffnet, ordnet jede Zeile der ganzen Zahl am Ende, und summiert dann die ganzen Zahlen:

zuerst die Datei öffnen:

Als nächstes müssen wir eine Funktion schreiben, die die letzte Spalte einer gegebenen Zeile als ganze Zahl zurückgibt.

def extract_last_int(line): 
    return int(line.split()[-1]) 

# apply 'extract_last_int' to each line, and then sum the results. 
print sum(map(extract_last_int, lines)) 
  • die .split() Methode wird auf den Feldern standardmäßig geteilt, Ihnen gibt eine Liste von jeder Spalte in dieser Zeile.

  • [-1] sagt Python, um das letzte Element der Liste zu erhalten.

  • map nimmt eine Funktion und eine Liste und ruft die Funktion einmal für jeden Punkt der Liste auf. Der Rückgabewert für map ist eine Liste der Ergebnisse jedes dieser Aufrufe. In diesem Fall ist der Rückgabewert von map eine Liste von Ganzzahlen, die sich in der letzten Spalte der Datei befinden.

  • Schließlich fügt sum alle diese ganzen Zahlen zusammen.

Das war's!

Wenn Sie neugierig sind, können Sie das gleiche tun mit awk in einer Zeile:

awk '{i+=$NF} END {print i}' my_file.txt