Search code examples
pythonarraysnumpydelimiter

Delimiting by Number of Characters


I am trying to delimit a 2D array that has no spaces in it. There are supposed to be 88 columns and 148 rows. But right now it's just 148 spaceless rows. The first row doesn't have any numbers and looks like this:

First Row


But there are rows that have numbers like this: *********************************************************************************************************************************************************************************************************************************************************************************************** 308. 308. 308. 308. 308. 308. 308. 308.*********************************************************************************************************************************************************************************************************************************************************************************

The goal is to delimit the rows every 7 characters to make 88 columns. The first two breaks would ideally look like this for each of the rows above:

Ideal result

and when it gets to the numbers in the second row I shared, it should look like this:

'*******', ' 308.'

(Doesn't really matter if the spaces in front of, or the period behind, the 308 is lost)

So far I've tried the following, with the file name being a .txt with the 2D array in it.

import numpy as np


a = input('Enter file name: \n')
a = np.loadtxt(a, dtype = 'i', delimiter = '\t')
b = [a[i:i+3] for i in range(0, len(a), 3)]

But I'm getting the following:

ValueError: could not convert string to float: '****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************'

I feel like it's probably an easy fix, but I have been spinning my wheels on it. Please help!


Solution

  • I read through your question a couple of times and it's not entirely clear to me what you want. You might have to reword your question and give more concrete and complete examples.

    If I am understanding your question correctly, you want to read in a text file and split the rows into 7-character chunks (though your example of " 308." is not 7 characters long). Numpy is not the ideal package to use for this problem. You can just use native Python methods.

    b = []
    with open("temp.txt", "r") as f:
        for a in f:
            a = a.rstrip()
            b.append([a[i:i+7] for i in range(0, len(a), 7)])