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
Calculate Cumulative Sum (Cumsum) by Group
Why Is the Parallel Package Slower Than Just Using Apply
Replace Multiple Letters With Accents With Gsub
Wrap Long Axis Labels Via Labeller=Label_Wrap in Ggplot2
How to Change the Default Library Path For R Packages
Quit and Restart a Clean R Session from Within R
How to Install Packages in Latest Version of Rstudio and R Version.3.1.1
R Apply() Function on Specific Dataframe Columns
Create Discrete Color Bar With Varying Interval Widths and No Spacing Between Legend Levels
How to Merge 2 Vectors Alternating Indexes
How to Replace Na Values in a Table For Selected Columns
Splitting a Continuous Variable into Equal Sized Groups
How to Divide Each Row of a Matrix by Elements of a Vector in R
R Install.Packages Returns "Failed to Create Lock Directory"