Shahin
Shahin

Reputation: 1316

adding columnar values from a file in python

I have the following file:

cat file.txt

1/1 2/3
2/3 1/3
./2 1/1
./. 3/2
1/1 ./.

I would like to remove the dots and add the numbers from each column (delimited by a slashe and a space).

So far, I have:

fp = open("file.txt","r")

for line in fp:
    cols = line.rstrip().split(" ")
    res = [int(cols[i][0]) for i in range(0,len(cols))].remove('.')
    print(sum(res))

I am trying to add the numbers before and after forward slash '/' in each column and output those delimited by '/'.

The expected output would be

4/7 7/9

Just one comment, the real file I'm working off of has more than 500 of these space delimited columns.

Upvotes: 0

Views: 21

Answers (1)

Rakesh
Rakesh

Reputation: 82765

Using str methods

Ex:

fp = """1/1 2/3
2/3 1/3
./2 1/1
./. 3/2
1/1 ./."""

c1, c2 = 0, 0
c3, c4 = 0, 0
for line in fp.splitlines():
    m, n = line.strip().split()
    m1, m2 = m.replace(".", "").split("/")
    n1, n2 = n.replace(".", "").split("/")
    if m1: c1 += int(m1)   #OR float(m1)
    if m2: c2 += int(m2)
    if n1: c3 += int(n1)
    if n2: c4 += int(n2)

print(f"{c1}/{c2} {c3}/{c4}")

Output:

4/7 7/9

Edit as per comment

result = [[0, 0] for i in range(2)] 
for line in fp.splitlines():
    row = line.strip().split()
    for idx, data in enumerate(row):
        m1, m2 = data.replace(".", "").split("/")
        if m1: result[idx][0] += int(m1)   #OR float(m1)
        if m2: result[idx][1] += int(m2)

print(result)

for m, n in result:
    print(f"{m}/{n}")

Output:

[[4, 7], [7, 9]]
4/7
7/9

Upvotes: 1

Related Questions