Python Forum
Selecting special values in txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Selecting special values in txt file
#1
Hello everyone,

Somme may remember a similar thread ...

I have txt files with the following structure :

Name = [102, 22]_[152, 32]_?_-20_-20
Mach = 0; Re = 2000000; T.U. = 1.0; T.L. = 1.0
Surface Finish = 0; Stall model = 0; Transition model = 1; Aspect Ratio = 0; ground effect = 0
?   Cl  Cd  Cm 0.25 T.U.    T.L.    S.U.    S.L.    L/D A.C.    C.P.
[°] [-] [-] [-] [-] [-] [-] [-] [-] [-] [-]
0.0 -2.868  0.02003 1.113   1.521   1.772   1.523   1.963   -143.170    0.250   0.638
Where the "?" sign (first line) can be 1,0 or -1.
I want to select the name of the file and the Cl and Cd values (-2.868 and 0.02003 in this particular case).
For know I used to convert the text into a string and did some slicing to get the name and the values.
But since "?"can be negative, this method doesn't work (slicing boundaries change) !!
Do you know an easy way to solve this problem ?
Thanks in advance,
Scientifix
Reply
#2
If I have understood well you want to parse the "Name = xxx" line to extract the numbers.
You can go in several paths to parse that line, each option is better depending on the variability of what you expect to find.
In any case I will never depend on the exact index of each separator in the string.

Maybe the easiest thing is manually:
def parse_name(txt):
    """
    Expect txt= '[102, 22]_[152, 32]_?_-20_-20'
    """
    def get_pair(s):
        return tuple(int(x) for x in s[1:-1].split(','))
    parts = txt.split('_')
    return get_pair(parts[0]), get_pair(parts[1]), int(parts[2]), int(parts[3]), int(parts[4])
parse_name('[102, 22]_[152, 32]_-5_-20_-20')
Output:
((102, 22), (152, 32), -5, -20, -20)
With regular expressions the things are more compact, but if you do not have experience with them might look like an invocation to Cthulhu:
import re
txt = '[102, 22]_[152, 32]_-5_-20_-20'
m = re.match(r'(?:\[(-?\d+),\s*(-?\d+)\]_){2}(-?\d+)_(-?\d+)_(-?\d+)', txt)
m.groups()
Output:
('152', '32', '-5', '-20', '-20')
To parse the body of the file I think the best options are either the csv module from the standard library or the loadtxt or genfromtxt from the numpy package.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Selecting first and last row in python sudhirkaukuntla 2 2,479 Oct-01-2019, 06:12 AM
Last Post: sudhirkaukuntla

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020