Seperating the numbers from strings to do the maths and return the string with the results [closed]

2024/11/20 19:32:39

I have some files like this. They are some receipts of restaurants.

---------------------------
CompanyID: 000000000000
ProductName: quantity costPerPizza sumCost
---------------------------

For example:

---------------------------
CompanyID: 000000000000
Pizza: 2   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80
---------------------------
CompanyID: 000000000001
burger: 1   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80
---------------------------

If the user gives input of a product name, I want to print the CompanyID and how many sales.

f=list(open(input('\nGive me the Filename: ')))
Answer

There are a few different components to this problem. First, how do you split the receipt into each individual company. Next you need to be able to parse the company's ID. Finally you need to be able to parse the quantity, cost, and total cost from a line item.

Splitting Receipts

Your method of splitting receipts depends on the separator. If you know that the number of hyphens is the same, you can split your input on that.

SEPARATOR = "---------------------------"with open('input-file.txt') as f:contents = f.read()# We only want to keep chunks of the file that have content.
company_receipts = []
for receipt in contents.split(SEPARATOR):if receipt.trim():company_receipts.append(receipt)

This should give you a list where each item is something like:

CompanyID: 000000000000
Pizza: 2   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80

Parsing Company IDs

The simple assumption here would be that the first line of every receipt is the company. We can use the same split operation we used before to separate the lines of the receipt as well as the parts of the line.

text = \
"""
CompanyID: 000000000000
Pizza: 2   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80
"""lines = text.split('\n')
company_line = lines[0]print(company_line.split(' '))
# Output: ['CompanyID:', '000000000000']

You can pull out the relevant parts of the line using their indices and you can convert strings to numbers with int(value).

Parsing Line Items

You can also use splits to get quantities, costs, and total costs from each line item. Using the lines variable from above:

# Remember lines also includes the company line, which we want to exclude
items = lines[1:]for item in items:item_components = item.split(' ')# Now you can pull out the components you wantitem_name = item_components[0]         # Example: 'Pizza:'item_cost = item_components[1].trim()  # Example: '3.15'

Since some of these components are decimals, you can parse them with float (instead of int), although with money you may want to deal with cents instead of dollars so everything is whole numbers and there are no rounding issues.

Compose

You should be able to use the logic laid out above to compose your own logic and accomplish your goal.

https://en.xdnf.cn/q/119798.html

Related Q&A

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

I want to Protect amy API by using OAuth 2.0 with Azure Active Directory and API Management. I have added my API in API management and Im following this article https://learn.microsoft.com/en-in/azure…

How can filter by list in django

I am trying to filter a queryset by a list I am getting unicode data into format of 1,4,5,6 bycategory = request.GET.getlist(category) print type(category)data = Leads.objects.filter(item_required__id…

Python: get the return code of ant sub-process in windows

I use python to call ant, I want to get the return code of the ant for detect ant error.for example, in cmd.exe, C:\Documents and Settings\Administrator>ant sfsf Buildfile: build.xml does not exist!…

Skipp the error while scraping a list of urls form a csv

I managed to scrape a list of urls from a CSV file, but I got a problem, the scraping stops when it hits a broken link. Also it prints a lot of None lines, is it possible to get rid of them ? Would ap…

Getting the TypeError - int object is not callable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Reordering columns in CSV

Question has been posted before but the requirements were not properly conveyed. I have a csv file with more than 1000 columns:A B C D .... X Y Z 1 0 0.5 5 .... 1 7 6 2 0 0.6 4 …

Variable not defined in while loop in python?

I am trying to write a simple program in python to read command line arguments and print a final word based on the arguments. If there is any argument of the form "-f=" then the will go to t…

Hours and time converting to a certain format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

Python socket server: listening to multiple clients [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

I have a problem with encoding with russian language for my python script [duplicate]

This question already has answers here:UnicodeEncodeError: ascii codec cant encode character u\xa0 in position 20: ordinal not in range(128)(34 answers)Closed last year.I am trying to send an email fro…