parse data

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • py

    #1

    parse data

    I have some data (in a string) such as....

    person number 1

    Name: bob
    Age: 50


    person number 2

    Name: jim
    Age: 39

    ....all that is stored in a string. I need to pull out the names of the
    different people and put them in a list or something. Any
    suggestions...b esides doing data.index("nam e")...over and over?

    thanks!

  • MooMaster

    #2
    Re: parse data

    If you know the indices of where the data should be in your string, you
    can use substrings... ie:
    [color=blue][color=green][color=darkred]
    >>> stringy = " Happy Happy Cow, 50, 1234 Your Mom's House AllTheTime,USA "
    >>> stringy[0:16][/color][/color][/color]
    ' Happy Happy Cow'

    If the data isn't set all the time (for example, and address doesn't
    have a mandatory length), then you're probably stuck using the index
    function...unle ss you have everything separated by a delimiter, such as
    a ","...then this would work:
    [color=blue][color=green][color=darkred]
    >>> listy = stringy.split(" ,")
    >>> print listy[/color][/color][/color]
    [' Happy Happy Cow', ' 50', " 1234 Your Mom's House AllTheTime", 'USA
    ']


    Hope this helps!

    Comment

    • MooMaster

      #3
      Re: parse data

      If you know the indices of where the data should be in your string, you
      can use substrings... ie:
      [color=blue][color=green][color=darkred]
      >>> stringy = " Happy Happy Cow, 50, 1234 Your Mom's House AllTheTime,USA "
      >>> stringy[0:16][/color][/color][/color]
      ' Happy Happy Cow'

      If the data isn't set all the time (for example, and address doesn't
      have a mandatory length), then you're probably stuck using the index
      function...unle ss you have everything separated by a delimiter, such as
      a ","...then this would work:
      [color=blue][color=green][color=darkred]
      >>> listy = stringy.split(" ,")
      >>> print listy[/color][/color][/color]
      [' Happy Happy Cow', ' 50', " 1234 Your Mom's House AllTheTime", 'USA
      ']


      Hope this helps!

      Comment

      • Dennis Benzinger

        #4
        Re: parse data

        py schrieb:[color=blue]
        > I have some data (in a string) such as....
        >
        > person number 1
        >
        > Name: bob
        > Age: 50
        >
        >
        > person number 2
        >
        > Name: jim
        > Age: 39
        >
        > ...all that is stored in a string. I need to pull out the names of the
        > different people and put them in a list or something. Any
        > suggestions...b esides doing data.index("nam e")...over and over?
        >
        > thanks!
        >[/color]

        Use the re module:


        import re

        your_data = """person number 1

        Name: bob
        Age: 50


        person number 2

        Name: jim
        Age: 39"""


        names = []

        for match in re.finditer("Na me:(.*)", your_data):
        names.append(ma tch.group(1))

        print names



        Bye,
        Dennis

        Comment

        • Micah Elliott

          #5
          Re: parse data

          On Nov 09, Dennis Benzinger wrote:[color=blue]
          > Use the re module:
          >
          > import re
          > your_data = """person number 1
          >
          > Name: bob
          > Age: 50
          >
          >
          > person number 2
          >
          > Name: jim
          > Age: 39"""
          >
          > names = []
          > for match in re.finditer("Na me:(.*)", your_data):
          > names.append(ma tch.group(1))
          > print names[/color]

          Dennis' solution is correct. If you want to avoid REs, and concision
          and speed are premiums, then you might refine it to:

          names = [line[5:].strip() for line in your_data.split ('\n')
          if line.startswith ('Name:')]

          --
          _ _ ___
          |V|icah |- lliott http://micah.elliott.name mde@micah.ellio tt.name
          " " """

          Comment

          • Larry Bates

            #6
            Re: parse data

            py wrote:[color=blue]
            > I have some data (in a string) such as....
            >
            > person number 1
            >
            > Name: bob
            > Age: 50
            >
            >
            > person number 2
            >
            > Name: jim
            > Age: 39
            >
            > ...all that is stored in a string. I need to pull out the names of the
            > different people and put them in a list or something. Any
            > suggestions...b esides doing data.index("nam e")...over and over?
            >
            > thanks!
            >[/color]
            Something like this works if line spacing can be depended on.
            Also a good way to hide the actual format of the string from your
            main program.

            Larry Bates

            class personClass:
            def __init__(self, nameline, ageline):
            self.name=namel ine.split(':')[1].strip()
            self.age=int(ag eline.split(':' )[1].strip())
            return

            class peopleClass:
            def __init__(self, initialstring):
            #
            # Define a list where I can store people
            #
            self.peoplelist =[]
            self.next_index =0
            #
            # Split the initial string on newlines
            #
            lines=initialst ring.split('\n' )
            #
            # Loop over the lines separating the people out
            #
            while 1:
            lines.pop(0) # Throw away the person number line
            bl1=lines.pop(0 ) # Throw away the blank line
            nameline=lines. pop(0) # Get name line
            ageline=lines.p op(0) # Get age line
            #
            # Create person instance and append to peoplelist
            #
            self.peoplelist .append(personC lass(nameline, ageline))
            try: bl2=lines.pop(0 ) # Throw away trailing blank line 1
            except: break # All done if there is none
            try: bl3=lines.pop(0 ) # Throw away trailing blank line 2
            except: break # All done if there is none

            return

            def __len__(self):
            return len(self.people list)

            def __iter__(self):
            return self

            def next(self):
            #
            # Try to get the next person
            #
            try: PERSON=self.peo plelist[self.next_index]
            except:
            self.next_index =0
            raise StopIteration
            #
            # Increment the index pointer for the next call
            #
            self.next_index +=1
            return PERSON

            if __name__== "__main__":
            initialstring=' person number 1\n\nName: bob\nAge: 50\n\n\n' \
            'person number 2\n\nName: jim\nAge: 39'
            people=peopleCl ass(initialstri ng)
            for person in people:
            print "Name:", person.name
            print "Age:", person.age

            Comment

            Working...