问题描述
我正在尝试读取此文本文件并显示其数据。我应该报告产品名称、其价值和最有价值的产品。我在最后添加了到目前为止我尝试做的事情:
Here is how the text file looks like:
item name 1 ex: hats
quantity of item 1 ex: 12
unit price of item 1 ex: 5.9
item name 2 ex: jacket
quantity of item 2 ex: 13
unit price of item 2 ex: 29.9
Expected output
12 hats at 5.9 the unit. total value: 70.8
13 jackets at 29.9 the unit. total value: 390
total inventory value: 460.8
most valuable inventory: jacket: 390
到目前为止我尝试过的:
filename = "store.txt"
with open(filename) as f:
content = f.read().splitlines()
content_list = [content[i * 3:(i + 1) * 3] for i in range((len(content) + 3 - 1) // 3)]
total_value = 0
for items in content_list:
value = float(items[2])*(float(items[1]))
print(items[1],'',items[0],'@ $',items[2],'. Value: $',value)
total_value += value
#max_value = max(value)
print('')
print('total value: '+ str(total_value))
#print('Highest value item: ' + str(max_value))
解决方法
有很多选择。这是一种入门方法(流行的方法):
filename = "file.py"
with open(filename) as f:
content = f.readlines()
print(content)
然后,您需要应用所需的逻辑(提取和操作文本)并将其写回不同的文件或作为输出提供。
,从您可以使用的文本文件中获取特定内容
python重新打包
link 如果想了解更多关于这个包的信息
re.split(pattern,string,flags=0)
这将返回一个列表
lis = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )]
n=size you want to break them in
my_list=the list you want to break
file = open("store.txt")
lis=[]
for line in file:
if(line.startswith("item")):
item_name=line[line.find(":")+1:]
lis.append(item_name.strip())
elif(line.startswith("quantity")):
quantity=line[line.find(":")+1:]
lis.append(float(quantity))
elif(line.startswith("unit")):
unit=line[line.find(":")+1:]
lis.append(float(unit))
content_list = [lis[i * 3:(i + 1) * 3] for i in range((len(lis) + 3 - 1) // 3)]
print(content_list)
total_value=0
lis2=[]
for items in content_list:
value = (items[2])*(items[1])
print(items[1],'',items[0],'@ $',items[2],'. Value: $',value)
lis2.append(value)
total_value+=value
max_value = max(lis2)
print('')
print('total value: '+ str(total_value))
print('Highest value item: ' + str(max_value))