#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    15
    Rep Power
    0

    Question Help with python


    I need to create a code which extracts a file which looks like this:
    Example 1
    This is line 2
    This is line 3


    I need to create a function which demands the file, and a word.
    It check's if the word is the starting words of each line, and returns the number of lines in which it is the first word.
    Example:
    if i extract the file above , and look for the word "This" , i should be return the value : 2.

    I didn't know how to check if the word is the first word in the line, so someone told me to use "startwith".
    Code:
     
    path=open("example1.txt","r")
    prefix="This"
    
    def count_lines_with_prefix(path, prefix):
        for line in path.readlines():
            count=0
            
            d=line.split()
            
            if d.startwith(prefix):
                count=count+1
            return count         
                
                
                
            
        
        
    d=count_lines_with_prefix(path, prefix)
    print d
    path.close()
    the problem is , i receive nemours errors such as, you can't use the "startwith" on a str, or a list.
    So i don't know what should i do.
    could you tell me how should i alter my code?
    thank you for your time.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    The correct string method is startswith() (note the second "s").
    >>> "abc def".startswith("ab")
    True
    Also, your split() statement, d=line.split(), is completely superfluous. Just use startswith on "line".
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    618
    Rep Power
    65
    Lines count=0 and return count should be outside the for loop.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo