我对Python很新鲜,需要帮助阅读txt文件中的信息。我有一个大的C++应用程序需要在Python中复制它。可悲的是,我不知道从哪里开始。我一直在阅读和看一些教程,但从他们那里得到的帮助很少,而且我没有时间。从Python中的txt文件中读取店铺列表
所以我的任务是: 我有一个购物清单:
项目,价格和年龄的杂牌。
我还需要创建两个搜索。
- 搜索商品是否在店内(比较字符串)。
if name of the item is == to the input name.
- 搜索由年龄。一旦程序找到这些项目,就需要根据价格打印清单 - 从最低价格到最高价格。
例如,您输入的年龄15 - 30,程序打印出适当的 项目,并通过价格排序。
任何帮助将是很好的。至少从我可以从哪里开始。 谢谢。
EDITED
到目前为止,我有这样的代码:
class data:
price = 0
agefrom = 0
ageto = 0
name = ''
# File reading
def reading():
with open('toys.txt') as fd:
toyslist = []
lines = fd.readlines()
for line in lines:
information = line.split()
print(information)
"""information2 = {
'price': int(information[1])
'ageftom': int(information[2])
'ageto': int(information[3])
#'name': information[4]
}"""
information2 = data()
information2.price = int(information[0])
information2.agefrom = int(information[1])
information2.ageto = int(information[2])
information2.name = information[3]
toyslist.append(information2)
return toyslist
information = reading()
我有这部分的问题。我想比较用户的输入与txt文件中的项目信息。
n_search = raw_input(" Please enter the toy you're looking for: ")
def name_search(information):
for data in information:
if data.name == n_search:
print ("We have this toy.")
else:
print ("Sorry, but we don't have this toy.")
那么,你可能需要一个'for'循环,比较'=='或'项[ ],正如Will所指出的那样,并且从像这样完成的文件中读取:'用inFile:records = inFile.readlines()'打开(“myFileName.txt”,“r”)。 '记录'将包含文件中的所有行,即' - 项目的名称,价格和年龄。 –
name_search在您的示例中用作变量和函数名称。其中一个会覆盖另一个 – Will
我错误地翻译了这个程序。在我的原始代码中,变量和函数的名称是不同的。就像我刚才提到的那样,它表示for循环出现错误。我无法理解为什么:| –