Count the Number of All Words in a String

Count the number of all words in a string

You can use strsplit and sapply functions

sapply(strsplit(str1, " "), length)

Python - Count number of words in a list strings

Use str.split:

>>> mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point  blanchardstown"] 
>>> for item in mylist:
... print len(item.split())
...
4
1
2
3

Counting words in string

Use square brackets, not parentheses:

str[i] === " "

Or charAt:

str.charAt(i) === " "

You could also do it with .split():

return str.split(' ').length;

How do I count the number of words in a text (string)?

You can try

sapply(gregexpr("\\S+", x), length)
## [1] 6 2 1 1

Or as suggested in comments you can try

sapply(strsplit(x, "\\s+"), length)
## [1] 6 2 1 1

How to find the count of a word in a string?

If you want to find the count of an individual word, just use count:

input_string.count("Hello")

Use collections.Counter and split() to tally up all the words:

from collections import Counter

words = input_string.split()
wordCount = Counter(words)

count the numbers of words only from string in python

You could try counting the number of terms which match \b[A-Za-z]+\b:

txt = "The rain in Spain3 3545 & %"
matches = re.findall(r'\b[A-Za-z]+\b', txt)
print(len(matches)) # 3

If on the other hand you want to define a word as being any number of alphanumeric characters so long as at least one letter be present, then you can use the above approach with the pattern \b\w*[A-Za-z]\w*\b:

txt = "The rain in Spain3 3545 & %"
matches = re.findall(r'\b\w*[A-Za-z]\w*\b', txt)
print(len(matches)) # 4

How do I count the number of words in a string?

Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:

String[] words = "Example test: one, two, three".split("[^A-Za-z]+");

EDIT: If you're just looking for raw speed, this'll do the job more quickly.

public static int countWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}


Related Topics



Leave a reply



Submit