Extracting text from alphanumeric strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Clemence
    New Member
    • Jul 2014
    • 1

    Extracting text from alphanumeric strings

    Hi There.

    I'm trying to write a code that reads the filenames of objects of the form "gal_z7.25. sae" and "gal_z0.02563.s ae" and stores the decimal digit parts ONLY to a list.

    So far I have the following:
    Code:
    import glob
    import sys, os
    
    #Open folder with files
    filelist = glob.glob("/home/clemence/Desktop/testing/*.sae")
    printing filelist gives me the following:

    /home/clemence/Desktop/testing/gal_z0.275.sae'

    And each item in filelist contains the numbers I need. All I need is a way of ignoring the text and taking only the numbers into another list.

    Please help
    Last edited by bvdet; Jul 22 '14, 06:38 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    This can be done with a regular expression.
    Code:
    >>> results = ["gal_z7.25.sae", "gal_z0.02563.sae"]
    >>> import re
    >>> patt = re.compile(r"[^0-9.]+([0-9]+.[0-9]+)")
    >>> for item in results:
    ... 	print patt.match(item).group(1)
    ... 	
    7.25
    0.02563
    >>>

    Comment

    Working...