我有以下输入数据,需要存储在适当的数据结构中。
Electronics
Electronics > Arcade Equipment
Electronics > Arcade Equipment > Basketball Arcade Games
Electronics > Arcade Equipment > Video Game Arcade Cabinets
Electronics > Audio
Electronics > Audio > Audio Accessories
Electronics > Audio > Audio Accessories > Audio & Video Receiver Accessories
Electronics > Audio > Audio Accessories > Headphone & Headset Accessories
Electronics > Audio > Audio Accessories > Headphone & Headset Accessories > Headphone Cushions & Tips
Apparel & Accessories > Clothing > Activewear > Hunting Clothing > Hunting & Tactical Pants
Apparel & Accessories > Clothing > Activewear > Martial Arts Shorts
Apparel & Accessories > Clothing > Activewear > Motorcycle Protective Clothing
Apparel & Accessories > Clothing > Baby & Toddler Clothing
Animals & Pet Supplies > Pet Supplies > Pet Grooming Supplies > Pet Nail Polish
其中应该提供以下信息。
我已经按照以下方式使用 python3 实现了,其时间复杂度为 O(n),其中 n 是文件中的行数。是否有其他有效的解决方案来存储上述信息。
def get_data(file_path):
try:
if not os.path.exists(file_path): # check file exist or not
raise FileNotFoundError
except FileNotFoundError:
print('please provide valid file path')
exit()
inventory = {}
with open(file=file_path, mode='r', encoding='utf-8') as file_descr:
try:
for line in file_descr:
line = line.strip()
llist = line.split('>') # list of keys
for i in range(1, len(llist) + 1): # check entry of each possible key in inventory
key = ('>'.join(llist[:i])).strip()
if inventory.get(key):
inventory[key] += 1
else:
inventory[key] = 1
except Exception as e:
print('not able to read content', e)
exit()
return inventory
幕布斯7119047
相关分类