Answers for "how to count words in a string python"

0

count words in string python

import string 

# sentence = ""
sentence = str(input("Enter here: "))

# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))

# Remove all numbers"
sentence = ''.join([Word for Word in sentence if not Word.isdigit()])

count = 0;

for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
        
print(count)
Posted by: Guest on May-31-2021
0

how to count words in string

String str = "I am happy and why not
  and why are you not happy and you should be";
        String [] arr = str.split(" ");
        Map<String, Integer> map = new HashMap<>();

        for (int i=0 ; i < arr.length ; i++){
                if (!map.containsKey(arr[i])){
                    map.put(arr[i],1);
                } else{
                    map.put(arr[i],map.get(arr[i])+1);
                }
        }
        for(Map.Entry<String, Integer> each : map.entrySet()){

  System.out.println(each.getKey()+" occures " + each.getValue() + " times");
        }
Posted by: Guest on January-22-2021
0

count words in string

// Count words (text separated by whitespace) in a piece of text
use std::collections::HashMap;

fn word_count(text: &str) -> HashMap<&str, i32> {
    let mut map = HashMap::new();
    for word in text.split_whitespace() {
        *map.entry(word).or_insert(0) += 1;
    }
    map
}

fn main() {
    println!("Count of words = {:?} ",word_count("the quick brown fox jumped over the lazy dog"));
}
Posted by: Guest on August-14-2021

Code answers related to "how to count words in a string python"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language