Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to count words in a string

I'm trying to analyze the contents of a string. If it has a punctuation mixed in the word I want to replace them with spaces.

For example, If Johnny.Appleseed!is:a*good&farmer is entered as an input then it should say there are 6 words, but my code only sees it as 0 words. I'm not sure how to remove an incorrect character.

FYI: I'm using python 3, also I can't import any libraries

string = input("type something")
stringss = string.split()

    for c in range(len(stringss)):
        for d in stringss[c]:
            if(stringss[c][d].isalnum != True):
                #something that removes stringss[c][d]
                total+=1
print("words: "+ str(total))
like image 406
Harry Harry Avatar asked Jul 06 '13 23:07

Harry Harry


People also ask

How do I count certain words in a string in word?

Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count words in a string in python?

Python Code:def word_count(str): counts = dict() words = str. split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog. '))

How do you count words in a string array?

Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.


1 Answers

How about using Counter from collections ?

import re
from collections import Counter

words = re.findall(r'\w+', string)
print (Counter(words))
like image 82
sweet_sugar Avatar answered Sep 25 '22 18:09

sweet_sugar