0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there a way to avoid having to initialize c1,c2,c3,c4? The actual file has 500 columns
Updated snippet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.