I'm fairly new to python, so bear with me, but I have a text file (opened with Path) with a dictionary in it and I'm trying to split it up into individual lines (without changing the file.) Some lines have multiple keys and indices separated by commas and some have only one to a line. I've tried re.split('\n |, ', lines) but I get the error:
'_io.TextIOWrapper' object has no attribute 'split'
file ex:
cake: dessert, kale: vegetable \n carrots: vegetable \n pears: fruit \n peaches: fruit \n peaches: fruit
Here's what I have now
def get_most_popular_foods(file_path):
""" Read in survey and determine the most common food of each type.
Parameters
----------
file_path : str
Path to text file containing favorite food survey responses.
Returns
-------
Dict[str, str]
Dictionary with the key being food type and value being food.
"""
from pathlib import Path
import re
path_to_file = Path(file_path)
with open(path_to_file, mode="r") as f:
lines = f.readlines()
lines2 = re.split('\n |, ', lines)
print(lines2)
I get the error "TypeError: expected string or bytes-like object" when I run this My end goal is to have it to where I can find the most popular of each type of food, so the result of this example would be
{'dessert': 'cake', 'vegetable': 'carrots', 'fruit': 'peaches'}
But I can get to the rest of the code another time, for now I just need to get list sorted out. I think having each index:key pair on individual lines would be best, but I'm open to sugestions.