Gitzee Gitzee - 1 month ago 6
Python Question

Python: Select particular characters from a file and add them to a new variable

I'm fairly new to python and I'm not sure why what I'm doing is wrong.

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)


I basically only want the numbers and commas within brackets. That's my biggest issue here.
The output I get for

print(listProducts)


is

]


Thank you.

Answer

Regarding your code, the solution is to:

  1. Removing the for theline in allOrders which is not coherent
  2. Moving the initialization of listProducts before the while loop

Of course this can be widely optimized using regex for example, as suggested by @tdelaney.

Comments