1

I am using cclib to parse some data from an output file. Using the below code:

filename = "calc.out"
data = cclib.io.ccread(filename)
print (data.grads)

I get the below output:

[[[-1.6510e-04 -4.4360e-04 -3.0450e-04]
  [ 4.8228e-03  3.2300e-05  1.0200e-05]
  [-1.9796e-03 -3.5266e-03 -2.6463e-03]
  [-1.6856e-03  4.7508e-03 -1.7005e-03]
  [-1.8385e-03 -9.7510e-04  4.8117e-03]]]

What I would like to do is convert the output to the below format:

-1.6510e-04
-4.4360e-04
-3.0450e-04
.
.
.
4.8117e-03

How would I do this with python? Please let me know if you need any additional information, I am new to asking questions and python. Thanks in advance for the help!

kskinnerx16
  • 127
  • 5

2 Answers2

1

Since the input you gave is not reproducible for me, I have edited it slightly to be legal python code (instead of the string output from some module I don't have).

Because I don't know the structure of your result sets, and you want to remove it anyway to get the requested output, I flattened it as:
https://stackoverflow.com/a/48262212/1766544

(I modified the above code slightly, because strings are iterable, but you want strings returned as-is, not character-by-character.)

You have indicated in comments that this yields strings which have multiple numbers inside them. It looks like they are simply space separated, so you will want to use str.split() https://docs.python.org/3.8/library/stdtypes.html?highlight=split#str.split

This third step with split() may have been the only part you needed, but I had to go through the other steps to get caught up, as the question didn't get me there.

data = [[['-1.6510e-04 -4.4360e-04 -3.0450e-04'],
         [' 4.8228e-03  3.2300e-05  1.0200e-05'],
         ['-1.9796e-03 -3.5266e-03 -2.6463e-03'],
         ['-1.6856e-03  4.7508e-03 -1.7005e-03'],
         ['-1.8385e-03 -9.7510e-04  4.8117e-03']]]

def flatten (data):
    for element in data:
        if isinstance(element, str):
            yield element
        else:
            try:
                yield from flatten(element)
            except TypeError:
                yield element

for item in flatten(data):
    for token in item.split():
        print (token)
Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30
  • Thanks for the help. How might I improve my question for the future? – kskinnerx16 Jul 28 '20 at 18:48
  • In the ideal case, someone can copy the code from your question, run it, and reproduce the issue [mcve] (notice you can do that with what I posted here, so if I misunderstood the question, you can immediately see where) – Kenny Ostrom Jul 28 '20 at 20:11
0

To print the desired output all you need to do is:

print(*(x for lst in data.grads for x in lst), sep='\n')
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50