【发布时间】:2017-02-25 17:37:05
【问题描述】:
我对 python 还很陌生,我不知道为什么我做错了。
numberOfOrders = 0
numberOfProducts = 0
allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file.
#file.txt:
#(A->[a:20,a:20,b:10,c:25,c:25])
#(B->[d:100,e:70])
#(C->[f:10000,g:200000])
while True:
theline = allOrders.readline()
for theline in allOrders:
for char in theline: #Iterate over each character of a line.
listProducts = "" #Empty string, will be the concatenation of the wanted characters.
if char == "[": #Wanted character.
listProducts = listProducts + "["
elif char == ":": #To keep count of no. of products in a list.
numberOfProducts += 1
elif is_number(char) == True: #Function that checks whether char is a number.
listProducts = listProducts + str(char) #Add to the string "listProducts".
elif char == ",": #Wanted character.
listProducts = listProducts + str(char)
elif char == "]":#Wanted character, to end the string.
listProducts = listProducts +str(char)
break
numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order.
if len(theline) == 0:
break
allOrders.close()
print(numberOfProducts)
print(numberOfOrders)
print(listProducts)
我基本上只想要括号内的数字和逗号。这是我在这里最大的问题。 我得到的输出
print(listProducts)
是
]
谢谢。
【问题讨论】:
-
你可以先去掉“for theline in allOrders:”这行似乎不合适...
-
您的文本文件是否与您在 cmets 中显示的一样完全? IE。是否包含“#(A->”和右括号?
-
添加您希望输出的样子。第一行是
20,20,10,25,25吗? -
文本文件不包含任何“#”,但包含所有其余部分。输出类似于:[20, 20, 10, 25, 25]。
-
你是指python列表还是有点像python列表的字符串?字符串转换为整数?看起来您真正想要的是订单和产品的数量。我要大胆猜测。
标签: python file python-3.x if-statement for-loop