0

I have a file with words separated by * and lines separated by ~, I would like to count the specific word how many times it is appeared in the file.

For eg.

Input File:

AB*xyz*1234~
CD*mny*769~
MN*bvd*2345~
AB*zar*987~

Code:

for (line <- bufferedSource.getLines()) {
      array = line.split("\\~")

for (row <- array ){
      val splittedRow=row.split("\\*")
      val cnt = splittedRow(0).contains("AB").count()

Here i am facing the issue in, how many times the word AB is present. Can you please help me how to get the count of specific words from an array. I am not able to use the keyword .count.

Kindly help me.

3 Answers 3

1

I made a small function for your case:

def count(term:String,file:File): Int = {
    Source.fromFile(file, "UTF-8").getLines().foldRight(0)((line, count) => {
        count + line.split("\\*").filter(_.contentEquals(term)).length
    })
}

println(count("AB",PATH_TO_INPUT)) // result is 2

all lines will check if there is your delimitter, filter the list of words to the term and add the length of remaining words to the current count value.

this helps me to understand fold methods

I hope that answer your question

Sign up to request clarification or add additional context in comments.

Comments

0
arr.map(_.split("\\*")).count(i => i.headOption.exists(_.contains("AB")))

count by contains function with first element and use Option to handle None.

5 Comments

Thanks for your reply!! with this i am getting the count from all the lines where ever it is matching. but i want only first word from all lines.
if i need to match only second word from all lines what should i use kindly help
such as: arr.lift(1).exists(_.contains("AB"))
Thanks For Reply Result is coming true false false false i need get count only
you should combine with count such as my answer.
0

the issue in, how many times the word AB is present. Can you please help me how to get the count of specific words from an array

You can read the file using Source api and then store the separated words in a list.

val resultArray = Source.fromFile(filename).getLines().flatMap(line => line.replace("~", "").split("\\*")).toList

You can count the number of repeatition of each words by call count function as

println(resultArray.count(_ == "AB"))   //will print 2
println(resultArray.count(_ == "CD"))   //will print 1
println(resultArray.count(_ == "xyz"))  //will print 1

I hope the answer is helpful

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.