user7373790
user7373790

Reputation:

Pulling a number out of a text file

I am trying to read in a text file that has many lines and on each line will be three numbers that I need to extracts. The textfile looks something like below:

Headerinformation

data/data_xrotate30_yrotate40_zrotate_50
data/data_xrotate31_yrotate49_zrotate2

so on and so forth.

importing the text file and reading the lines is relatively straightforward:

DataRotations = 'data.txt'

"""Next we open each text file"""

DataRotationsOpen = open(DataRotations, "r")
DataRotationsRead = DataRotationsOpen.readlines()

I can then just split each line by the '_' that is also easy enough:

variable = 'data'
for line in ArtificialDataRotationsRead:
    if variable in line:
        currentline = line.split('_')

However if I then try and split the data up further to extract the numbers I run into an issue. I have tried:

variable = 'data'
for line in ArtificialDataRotationsRead:
    if variable in line:
        currentline = line.split('_')
        X = re.search(r'\d', currentline[1])  

but this does not work.

I also tried

Number = [int(a) for a in currentline[1] if a.isdigit()]

but this did not work.

Are there any other ways to do this?

Upvotes: 0

Views: 52

Answers (2)

ChaosPredictor
ChaosPredictor

Reputation: 4051

you can do something like this:

s = "data/data_xrotate30_yrotate40_zrotate_50"
s2 = s.split('_')
for s3 in s2:
    t = ''.join([i for i in s3 if i.isdigit()])
    if t:
        print(t)

Upvotes: 1

Macio
Macio

Reputation: 124

import re
print(re.findall(r'\d+', 'data/data_xrotate30_yrotate40_zrotate_50'))

and result is

['30', '40', '50']

Upvotes: 0

Related Questions