Counting a desired word in a text file










2















I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:



'nation' is found 0 times in the file gettysburg.txt


Here is the code I have currently, could someone point out what I am doing incorrectly?



fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None

def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")

if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)


My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.



Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.










share|improve this question



















  • 1





    did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

    – kpie
    Nov 15 '18 at 1:15











  • @kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

    – H. Raydon
    Nov 15 '18 at 1:19






  • 1





    hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

    – jeevs
    Nov 15 '18 at 1:21







  • 1





    as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

    – Joran Beasley
    Nov 15 '18 at 1:26
















2















I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:



'nation' is found 0 times in the file gettysburg.txt


Here is the code I have currently, could someone point out what I am doing incorrectly?



fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None

def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")

if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)


My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.



Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.










share|improve this question



















  • 1





    did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

    – kpie
    Nov 15 '18 at 1:15











  • @kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

    – H. Raydon
    Nov 15 '18 at 1:19






  • 1





    hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

    – jeevs
    Nov 15 '18 at 1:21







  • 1





    as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

    – Joran Beasley
    Nov 15 '18 at 1:26














2












2








2








I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:



'nation' is found 0 times in the file gettysburg.txt


Here is the code I have currently, could someone point out what I am doing incorrectly?



fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None

def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")

if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)


My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.



Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.










share|improve this question
















I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:



'nation' is found 0 times in the file gettysburg.txt


Here is the code I have currently, could someone point out what I am doing incorrectly?



fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None

def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")

if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)


My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.



Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.







python python-3.x file loops counting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 1:29









martineau

69.6k1092186




69.6k1092186










asked Nov 15 '18 at 1:06









H. RaydonH. Raydon

634




634







  • 1





    did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

    – kpie
    Nov 15 '18 at 1:15











  • @kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

    – H. Raydon
    Nov 15 '18 at 1:19






  • 1





    hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

    – jeevs
    Nov 15 '18 at 1:21







  • 1





    as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

    – Joran Beasley
    Nov 15 '18 at 1:26













  • 1





    did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

    – kpie
    Nov 15 '18 at 1:15











  • @kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

    – H. Raydon
    Nov 15 '18 at 1:19






  • 1





    hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

    – jeevs
    Nov 15 '18 at 1:21







  • 1





    as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

    – Joran Beasley
    Nov 15 '18 at 1:26








1




1





did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

– kpie
Nov 15 '18 at 1:15





did you make sure to save the text to gettysburg.txt? I would replace punctuation with "" not " " but otherwise this should be straight.

– kpie
Nov 15 '18 at 1:15













@kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

– H. Raydon
Nov 15 '18 at 1:19





@kpie I did save the file and just double checked to ensure. I made the suggested edits as well. Thank you for your help!

– H. Raydon
Nov 15 '18 at 1:19




1




1





hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

– jeevs
Nov 15 '18 at 1:21






hi @H.Raydon, here are the steps i would follow: 1. Verify that file is in the same directory as the place where the script is run 2. verify that the length of words is greater than 0. 3. change the processone function to accept a parameter and return the output of the split call.

– jeevs
Nov 15 '18 at 1:21





1




1





as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

– Joran Beasley
Nov 15 '18 at 1:26






as an aside it think you could just use a regular expression len(re.findall("(?:b|^)nation(?:b|$)",text,re.IGNORE_CASE))

– Joran Beasley
Nov 15 '18 at 1:26













3 Answers
3






active

oldest

votes


















4














In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.



You probably want to move the return statement to be outside of the for loop.






share|improve this answer























  • This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

    – H. Raydon
    Nov 15 '18 at 1:24






  • 1





    wow, I spent five minutes looking and didn't see that :o Shame on me.

    – kpie
    Nov 15 '18 at 1:27


















0














as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.



def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
print (word)
if word == token:
count += 1
return count


Enter a file name to process:gettysburg.txt
Enter a word to search for:nation
fourscore
'nation' is found 0 times in the file gettysburg.txt





share|improve this answer






























    0














    Use code below:



    fname = input("Enter a file name to process:")
    find = input("Enter a word to search for:")
    text = open(fname, 'r').read()
    def processone():
    if text is not None:
    words = text.lower().split()
    return words
    else:
    return None

    def count_word(tokens, token):
    count = 0
    for element in tokens:
    word = element.replace(",", " ")
    word = word.replace("."," ")

    if word == token:
    count += 1
    return count

    words = processone()

    word = find
    frequency = count_word(words, word)
    print("'"+find+"'", "is found", str(frequency), "times in the file", fname)



    statement "return" go out statement "for"






    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311024%2fcounting-a-desired-word-in-a-text-file%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.



      You probably want to move the return statement to be outside of the for loop.






      share|improve this answer























      • This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

        – H. Raydon
        Nov 15 '18 at 1:24






      • 1





        wow, I spent five minutes looking and didn't see that :o Shame on me.

        – kpie
        Nov 15 '18 at 1:27















      4














      In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.



      You probably want to move the return statement to be outside of the for loop.






      share|improve this answer























      • This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

        – H. Raydon
        Nov 15 '18 at 1:24






      • 1





        wow, I spent five minutes looking and didn't see that :o Shame on me.

        – kpie
        Nov 15 '18 at 1:27













      4












      4








      4







      In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.



      You probably want to move the return statement to be outside of the for loop.






      share|improve this answer













      In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.



      You probably want to move the return statement to be outside of the for loop.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 15 '18 at 1:20









      John GordonJohn Gordon

      10.5k51831




      10.5k51831












      • This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

        – H. Raydon
        Nov 15 '18 at 1:24






      • 1





        wow, I spent five minutes looking and didn't see that :o Shame on me.

        – kpie
        Nov 15 '18 at 1:27

















      • This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

        – H. Raydon
        Nov 15 '18 at 1:24






      • 1





        wow, I spent five minutes looking and didn't see that :o Shame on me.

        – kpie
        Nov 15 '18 at 1:27
















      This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

      – H. Raydon
      Nov 15 '18 at 1:24





      This fixed my issue! Thank you for the finding my mistake and assisting me in fixing it.

      – H. Raydon
      Nov 15 '18 at 1:24




      1




      1





      wow, I spent five minutes looking and didn't see that :o Shame on me.

      – kpie
      Nov 15 '18 at 1:27





      wow, I spent five minutes looking and didn't see that :o Shame on me.

      – kpie
      Nov 15 '18 at 1:27













      0














      as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.



      def count_word(tokens, token):
      count = 0
      for element in tokens:
      word = element.replace(",", " ")
      word = word.replace("."," ")
      print (word)
      if word == token:
      count += 1
      return count


      Enter a file name to process:gettysburg.txt
      Enter a word to search for:nation
      fourscore
      'nation' is found 0 times in the file gettysburg.txt





      share|improve this answer



























        0














        as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.



        def count_word(tokens, token):
        count = 0
        for element in tokens:
        word = element.replace(",", " ")
        word = word.replace("."," ")
        print (word)
        if word == token:
        count += 1
        return count


        Enter a file name to process:gettysburg.txt
        Enter a word to search for:nation
        fourscore
        'nation' is found 0 times in the file gettysburg.txt





        share|improve this answer

























          0












          0








          0







          as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.



          def count_word(tokens, token):
          count = 0
          for element in tokens:
          word = element.replace(",", " ")
          word = word.replace("."," ")
          print (word)
          if word == token:
          count += 1
          return count


          Enter a file name to process:gettysburg.txt
          Enter a word to search for:nation
          fourscore
          'nation' is found 0 times in the file gettysburg.txt





          share|improve this answer













          as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.



          def count_word(tokens, token):
          count = 0
          for element in tokens:
          word = element.replace(",", " ")
          word = word.replace("."," ")
          print (word)
          if word == token:
          count += 1
          return count


          Enter a file name to process:gettysburg.txt
          Enter a word to search for:nation
          fourscore
          'nation' is found 0 times in the file gettysburg.txt






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 1:32









          KalanguKalangu

          566




          566





















              0














              Use code below:



              fname = input("Enter a file name to process:")
              find = input("Enter a word to search for:")
              text = open(fname, 'r').read()
              def processone():
              if text is not None:
              words = text.lower().split()
              return words
              else:
              return None

              def count_word(tokens, token):
              count = 0
              for element in tokens:
              word = element.replace(",", " ")
              word = word.replace("."," ")

              if word == token:
              count += 1
              return count

              words = processone()

              word = find
              frequency = count_word(words, word)
              print("'"+find+"'", "is found", str(frequency), "times in the file", fname)



              statement "return" go out statement "for"






              share|improve this answer



























                0














                Use code below:



                fname = input("Enter a file name to process:")
                find = input("Enter a word to search for:")
                text = open(fname, 'r').read()
                def processone():
                if text is not None:
                words = text.lower().split()
                return words
                else:
                return None

                def count_word(tokens, token):
                count = 0
                for element in tokens:
                word = element.replace(",", " ")
                word = word.replace("."," ")

                if word == token:
                count += 1
                return count

                words = processone()

                word = find
                frequency = count_word(words, word)
                print("'"+find+"'", "is found", str(frequency), "times in the file", fname)



                statement "return" go out statement "for"






                share|improve this answer

























                  0












                  0








                  0







                  Use code below:



                  fname = input("Enter a file name to process:")
                  find = input("Enter a word to search for:")
                  text = open(fname, 'r').read()
                  def processone():
                  if text is not None:
                  words = text.lower().split()
                  return words
                  else:
                  return None

                  def count_word(tokens, token):
                  count = 0
                  for element in tokens:
                  word = element.replace(",", " ")
                  word = word.replace("."," ")

                  if word == token:
                  count += 1
                  return count

                  words = processone()

                  word = find
                  frequency = count_word(words, word)
                  print("'"+find+"'", "is found", str(frequency), "times in the file", fname)



                  statement "return" go out statement "for"






                  share|improve this answer













                  Use code below:



                  fname = input("Enter a file name to process:")
                  find = input("Enter a word to search for:")
                  text = open(fname, 'r').read()
                  def processone():
                  if text is not None:
                  words = text.lower().split()
                  return words
                  else:
                  return None

                  def count_word(tokens, token):
                  count = 0
                  for element in tokens:
                  word = element.replace(",", " ")
                  word = word.replace("."," ")

                  if word == token:
                  count += 1
                  return count

                  words = processone()

                  word = find
                  frequency = count_word(words, word)
                  print("'"+find+"'", "is found", str(frequency), "times in the file", fname)



                  statement "return" go out statement "for"







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 2:18









                  K. WinfredK. Winfred

                  1




                  1



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311024%2fcounting-a-desired-word-in-a-text-file%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kleinkühnau

                      Makov (Slowakei)

                      Deutsches Schauspielhaus