2

I have a string series[Episode 37]-03th_July_2010-YouTube and I want to extract the number which comes directly after Episode (eg: 37 from Episode 37)the position ofEpisode 37` may not be fixed in the string. I tried:

def extract_episode_num(self,epiname):
    self.epiname = epiname
    try:
        self.temp = ((self.epiname.split('['))[1]).split(']')[0]    #extracting the Episode xx from episode name
    except IndexError:                                              #to raise exception if episode name is not in format
        print'wrong file name or Episodes have finished'
        raise
    else:
        return re.findall('\d+',self.temp)  

but the code is dependent of [] brackets. How do I make the code better?

2 Answers 2

6

Regular expressions to the rescue!

I see you are already on the right path, by using a regular expression. But you could try using a regular expression with a capture in order to capture the digits following the string "Episode".

Here is a small example to get you going:

import re
m = re.search('Episode (\d+)', 'series[Episode 37]-03th_July_2010-YouTube', re.IGNORECASE)
m.group(1)

The last statement, m.group(1), returns the contents of the first group (what's inside the parentheses in the regular expression). In this case it will be the string '37', which is the digits that follows the string "Episode ".

Also notice I'm using the IGNORECASE flag, so this will work regardless of the casing of the string "Episode". So "episode" and even "ePISODE" will work too.

1
  • Edit: Changed the code example to use re.search instead of precompiled regex.
    – arntjw
    Oct 17, 2016 at 8:23
1

Kind of broad, pulling from a text file, but will do for many applications of getting both integers and floats out of strings.

The file, commaseperated.txt has a row looking like this:

Input: (0, 1, 2.4), 1, 5, 8, 99.7, 0.1), (, )()!@!#, 9
    import re


    # a function to pull the numbers from many lists of strings
    def func(a, z, c):
        # -- Read .txt -- #
        filename = 'commaseperated.txt'
        f1 = open(filename, 'r')  # open the file for reading
        data = f1.readlines()  # read the entire file as a list of strings
        f1.close()
        #
        for line in data:
            cells = line.strip().split(',')
            # empty string
            b = ""
            # range through cells of from a text file split by commas
            for i in range(a, len(cells[z:c])+a):
                # no commas in the cells so make dummy commas for new string
                b += cells[i] + ','
            # find all the numbers
            z = re.findall(r'\d+(?:\.\d+)?', b)
            # return a list of floated values from the text string
            return [float(z[s]) for s in range(len(z))]
    Output: [0, 1, 2.4, 1, 5, 8, 99.7, 0.1, 9]

Not the answer you're looking for? Browse other questions tagged or ask your own question.