Regarding searching of strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bkunjitam
    New Member
    • Nov 2006
    • 17

    Regarding searching of strings

    i am a beginner in Python. I have a query.

    I have a .txt file which has entries in the following manner:

    Name: John
    Age: 21

    Name: Paul
    Age:23

    I need to search for the string "Name" and display all the values corresponding to the string that i am searching for. In this case the result should be John and Paul.
    I am a bit confused with the re.search() function.

    Kindly guide me regarding the same.

    Regards,
    BK
  • fuffens
    New Member
    • Oct 2006
    • 38

    #2
    If names always start with Name: in your file and is separated by a white space then this should do it

    Code:
    file = open('name.txt', 'r')
    for line in file:
        if line.startswith('Name:'):
            name = line.split()[1]
            print name
    file.close()
    Use regular expressions for more compex search operations. Here you only need to find Name: so you can use normal string operations like startswith() or find().

    Best regards
    /Fredrik

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Originally posted by bkunjitam
      i am a beginner in Python. I have a query.

      I have a .txt file which has entries in the following manner:

      Name: John
      Age: 21

      Name: Paul
      Age:23

      I need to search for the string "Name" and display all the values corresponding to the string that i am searching for. In this case the result should be John and Paul.
      I am a bit confused with the re.search() function.

      Kindly guide me regarding the same.

      Regards,
      BK
      I wrote a script to run in SDS/2 (software for structural steel detailing) that does something similar. The input file format is:
      Origin:0.0,0.0
      Direction:-90.0
      41-5
      42-8
      ......additiona l offset dimensions

      Origin:0.0,0.0
      Direction:0.0
      1-11 1/2
      1-0 1/2
      .......addition al offset dimensions
      The object of this script is to layout building grid lines in a plan view of the 3D model. Here's the code:
      Code:
      def run_script():
          try:
              from param import ResponseNotOK, Units, Dialog, Warning, dim
              from macrolib.ExceptWarn import formatExceptionInfo
              from macrolib.PolarPt import polar_pt_plan
              from point import Point
              from job import JobName
              from cons_line import ConsLine
              import os
              import string
              Units("feet")
              
              #####################################    
              def gridAdd(pt, dir, cons_color="Cyan"):
                  # construction line begin
                  cl2 = ConsLine()
                  cl2.pt1 = pt
                  cl2.angle = dir
                  cl2.pen = cons_color
                  cl2.add()
                  # construction line end
              ####################################
              
              ## Dialog Box ######################
              dlg1 = Dialog("Building Grid Lines in Plan")
              dlg1.group_title("Import Grid Line File")
              dlg1.file('import_file', os.path.join(os.getcwd(), "jobs", JobName(), "macro", "TownCtrGrids.txt"), "Enter file name or browse       ")
              dlg1.menu('cons_color', ("Blue", "Green", "Yellow", "Magenta", "Red", "White", "Cyan"), "Blue", "Construction line color")
              
              try:
                  dlg1.done()
              except ResponseNotOK:
                  raise
              
              # Import grid line file
              try:
                  f = open(dlg1.import_file, "r")
              except IOError, e:
                  # unable to open file
                  Warning("Unable to open file: %s" % (e))
      
              for item in f:
                  if "origin" in string.lower(item):
                      ptx, pty = item.split(':')[1].split(",")                    
                      gridWP = Point(dim(ptx.strip()), dim(pty.strip()), 0.0)
                  elif "direction" in string.lower(item):
                      gridOffset = 0.0
                      gridDir = dim(item.split(':')[1].strip())
                      gridAdd(gridWP, gridDir, dlg1.cons_color)
                  else:
                      if dim(item.strip()):
                          gridOffset = gridOffset + dim(item.strip())
                          gridAdd(polar_pt_plan(gridWP, gridOffset, gridDir + 90.0), gridDir, dlg1.cons_color)
              f.close()
          except:
              Warning(formatExceptionInfo())
      ## END run_script() #########################
      if __name__ == '__main__':
          try:
              run_script()
          finally:
              del run_script
      Thanks to this list for the pointers received!
      Last edited by bvdet; Nov 8 '06, 11:53 PM. Reason: code correction

      Comment

      • bkunjitam
        New Member
        • Nov 2006
        • 17

        #4
        Originally posted by fuffens
        If names always start with Name: in your file and is separated by a white space then this should do it

        Code:
        file = open('name.txt', 'r')
        for line in file:
            if line.startswith('Name:'):
                name = line.split()[1]
                print name
        file.close()
        Use regular expressions for more compex search operations. Here you only need to find Name: so you can use normal string operations like startswith() or find().

        Best regards
        /Fredrik

        Hi,

        As far as my understanding goes, its only when it starts with "Name:" i can use the code snippet provided. But what if i need to search for the string "Name:" and display the values corresponding to it.

        e.g if i have a format like mentioned below:

        ### Name: John
        Age: 23

        *** Name: Paul
        Age: 24

        Here how do i go about searching for the string "Name:" and displaying all the matching content for the string on the screen.

        Kindly clarify my doubt.

        Thanks,
        BK

        Comment

        • fuffens
          New Member
          • Oct 2006
          • 38

          #5
          This will do it...

          Code:
          file = open('name.txt', 'r')
          for line in file:
              if line.find('Name:') >= 0:
                  name = line.split()[-1]
                  print name
          file.close()
          You can use find to check if a string is included in a string. It will return a negative number if not included. You can still use split() to extract the name. [-1] will give you the last element of the split list.

          /Fredrik

          Comment

          • bkunjitam
            New Member
            • Nov 2006
            • 17

            #6
            Originally posted by fuffens
            This will do it...

            Code:
            file = open('name.txt', 'r')
            for line in file:
                if line.find('Name:') >= 0:
                    name = line.split()[-1]
                    print name
            file.close()
            You can use find to check if a string is included in a string. It will return a negative number if not included. You can still use split() to extract the name. [-1] will give you the last element of the split list.

            /Fredrik

            Thanks a lot Fredrik. It was very helpful

            Thanks,
            BK

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              This works also:
              Code:
              if 'Name' in line:

              Comment

              Working...