Reputation: 33
I have a text file with multiple lines all with the numbers ranging from 1 to 5 in the following format: '1,2,3,4,5'
. I want to read every line of the text file. On each line I want to find the '1'.
I then want to increase the value of a list value by 1, depending on the position of the '1' in the text file. E.g. if the '1' is in position 0 in the text file, I want the lists position 0 to be increased by 1 (for every line in the text file).
My current code is not reading the text file, therefore it is not reading the '1' on each line and carrying out the function I described above. Here's my code (sorry for the lengthy explanation):
with open("test file.txt","r+") as file:
oneNum = [0,0,0,0,0]
text = [line.rstrip("\n") for line in open("test file.txt")]
for line in text:
for counter in range(0,4):
if line[counter] == "1":
oneNum[counter] = oneNum[counter] + 1
Upvotes: 2
Views: 84
Reputation: 123531
Using Python's regular expressions module, re
makes this easy to do. For example, say this was the input file's contents:
1,2,3,4,5
2,1,3,4,5
3,2,1,4,5
4,5,1,3,2
and this is code show how to use re
to solve the problem. Note how removing the ','
characters allows the position of the matching character to be used to update the corresponding counter.
import re
oneNum = [0, 0, 0, 0, 0]
with open("test file.txt") as file:
pattern = r"1"
for line in file:
line = line.strip().replace(',', '')
match = re.search(pattern, line)
if match:
counter = match.span()[0]
oneNum[counter] += 1
print(oneNum) # -> [1, 1, 2, 0, 0]
Upvotes: 0
Reputation: 124824
Given the simple input format as described in the question, the implementation can be simplified (and corrected):
oneNum
with zerosoneNum
Like this:
with open("test file.txt") as file:
oneNum = [0] * 5
for line in file:
index = line.find("1") // 2
oneNum[index] += 1
Upvotes: 1
Reputation: 6113
with open("test file.txt", "r+") as file:
oneNum = [0 for _ in range(5)] # Easier to adjust later
for line in file:
position = [num.strip() for num in line.split(',')].index('1')
oneNum[position] += 1
Upvotes: 0