how to count spaces in a file in python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thistle
    New Member
    • Mar 2015
    • 9

    how to count spaces in a file in python?

    I want to write a function that takes a file and a character and returns the number of character, the character is space for example.I wrote the code below but it doesn't work.
    Code:
    def c (file, char):
        f = open ('file1.txt', 'r')
        s = f.read()
        i = 0
        for char in s:
            i += 1
    Last edited by bvdet; Mar 12 '15, 05:43 PM. Reason: Please use code tags when posting code [code]....[/code]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Maybe this will help. I have a string s with 2 commas in it.
    Code:
    >>> char = ","
    >>> i = 0
    >>> for letter in s:
    ... 	if letter == char:
    ... 		i+=1
    ... 		
    >>> i
    2
    >>>
    Return the character count i at the end of the function definition.
    Code:
        return i

    Comment

    • thistle
      New Member
      • Mar 2015
      • 9

      #3
      thanks. but I want a function and it should take a file not a string. How should I write a function?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        It won't help you if I write the function for you. You already have a string assigned to s in the function you wrote. I gave you the for loop to count the characters. Substitute it for your for loop and add the return statement. BTW, anytime you create an open file object, it is good practice to close it when you are done. Otherwise you could read the file without creating a file object:
        Code:
        s = open('file1.txt').read()

        Comment

        • thistle
          New Member
          • Mar 2015
          • 9

          #5
          Code:
          def C (file, char):
              f = open ('file1.txt', 'r')
              s = f.read()
              i = 0
              for ch in s:
                  if ch == char:
                      i += 1
              return i
          Last edited by bvdet; Mar 12 '15, 11:17 PM. Reason: Please use code tags when posting code [code]....[/code]

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            thistle,

            Please use code tags when posting code.

            Don't forget the close the file object.
            f.close()

            Comment

            Working...