Friday, 9 February 2018

Textwrap: Impressive python module

I am currently reverse-engineering an audio analysis algorithm which computes for the statistical variance. I needed to get around 100,000 A/D data points from the MSP430's FRAM microcontroller so that I can inject it to my unit test. With that, IAR gives me a TI-TXT format.

example:
@10000
30 20 40 50
60 70 80 90

I needed to convert this to a C array so that I can place this inside my C++ code. Here are the steps I did:

1. I extracted all the data and placed them inside a list which is very easy to do using split, appending "0x" and using join. The output will be like this:
"0x30, 0x20, 0x60"  so on so forth

2. My problem with the above string is that it will take only one line of my C++ code which I feel won't look nice as I don't want to be scrolling horizontally as much as possible. I thought of creating a python algorithm to put newlines nicely without cutting a whole string like:
0x30, 0x20 ,0x
60, 0x70, 0x8
0, 0x20

Then I discovered python already covers it for me via textwrap module which I think is a smart algorithm. So now, I won't have any broken string and it will be printed nicely:

0x30, 0x20 ,0x60,
0x70, 0x80, 0x20

More information on how to use it here:  https://pymotw.com/2/textwrap/

No comments:

Post a Comment