'Python: How to sum numbers in text file with strings when meet conditions
I'm doing an inventory system which require for me to print distribution list of particular item. If the particular item has distribute to the same hospital for more than 1 time, it need to sum the quantity together.
The code that i'm writing now only allow for me to print the distribution list, it won't sum the quantity together if the item code and hospital code is same. (Check with code but not name to sum it up) How can i make it sum up together if hospital code and item code is same?
I'm only allow to use list, dictionary and pandas are not allowed.
def search_functions():
try:
fhand = open("distribution.txt","r")
except:
print("You haven't distribute any item yet!\n")
searchInput = input("\nEnter item code to search: ")
print()
for line in fhand:
lines = line.strip()
if searchInput.lower() in lines.lower():
print(lines)
continue
print()
fhand.close()
search_functions()
Inside the text file
first item is hospital code, second is name, 3rd is item code, 4th is item name and the last one is quantity.
distribution.txt text file
HSPT001,Care Medical Hospital,HC,Head Cover,9
HSPT001,Care Medical Hospital,HC,Head Cover,6
HSPT002,Community Health Service,HC,Head Cover,7
The output need to be like below, when the searchinput is HC
HSPT001, Care Medical Hospital, HC, Head Cover, 15
HSPT002, Community Health Service, HC, Head Cover, 7
instead of
HSPT001,Care Medical Hospital,HC,Head Cover,9
HSPT001,Care Medical Hospital,HC,Head Cover,6
HSPT002, Community Health Service, HC, Head Cover, 7
Solution 1:[1]
worked on your issue using pandas, and below code solves it:
import pandas as pd
# "hospital_code", "name","item_code","item_name","quantity"
data = pd.read_csv("distribution_list.txt",names=["hospital_code", "name","item_code","item_name","quantity"])
print(data.groupby(["hospital_code", "name","item_code","item_name"]).sum())
Solution 2:[2]
You can use defaultdict for this:
from collections import defaultdict
result = defaultdict(float)
with open("distribution.txt") as f:
data = f.read().split("\n")
data = [line.strip().lower() for line in data]
for line in data:
elements = line.split(",")
# ["HSPT001", "Care Medical Hospital", "HC", "Head Cover", "6"]
if len(elements) != 5:
continue
item_code = elements[2].lower().strip() # "hc"
quantity = float(elements[-1].strip()) # "6"
result[item_code] += quantity
searchInput = input("\nEnter item code to search: ").strip().lower()
print(result.get(searchInput, 0))
If your are not allowed to use dict then just add quantity to a variable:
result = 0
for line in data:
elements = line.split(",")
# ["HSPT001", "Care Medical Hospital", "HC", "Head Cover", "6"]
if len(elements) != 5:
continue
item_code = elements[2].lower().strip() # "hc"
quantity = float(elements[-1].strip()) # "6"
result += quantity
Solution 3:[3]
try it, use pandas
import pandas as pd
df = pd.read_table("distribution.txt text file", sep=",", names=["hospital_code", "name","item_code","item_name","quantity"])
group_df = df.groupby(["hospital_code", "name","item_code","item_name"]).sum().reset_index()
for idx, row in group_df.iterrows():
for col in ["hospital_code", "name","item_code","item_name","quantity"]:
print(row[col], end=" ")
print()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anzuman farhana |
| Solution 2 | |
| Solution 3 | maya |
