Reputation:
I have a text file containing items and their properties, and I'd like to split them into separate items in a list. For example, this is what one line in the text file looks like:
Garlic Bread 100g 400kCal 4g 200mg
I have to create functions where you can search for food items by name, by calories, fat, etc. I know how to split them into a list where it's like ['Garlic', 'Bread', '100g' '400kCal', '4g', '200mg']
, but my goal is to have it like ['Garlic Bread 100g', '400kCal', '4g', '200mg']
I used this code below, but lets say I input 100g, the program also outputs other food items that don't contain '100g' in the title, but rather somewhere else (like sodium content)
itemsearch = input("Enter a food item: ")
itemsearch = [item.strip() for item in itemsearch.lower().split(",")]
with open("nutriton.txt") as TxtFile:
for thing in TxtFile:
for item in itemsearch:
if item in thing:
print(thing)
Sorry if my explanation is a little confusing. I think I have to do something with item[:1], but I would need to have the list items separated properly.
Upvotes: 0
Views: 137
Reputation: 12168
import re
line = 'Garlic Bread 100g 400kCal 4g 200mg'
split_list = re.split(r'\s{2,}', line)
print(split_list)
out:
['Garlic Bread 100g', '400kCal', '4g', '200mg']
Upvotes: 1