Reputation: 297
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.
Upvotes: 0
Views: 149
Reputation: 175
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
Upvotes: 1
Reputation: 41957
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
Upvotes: 0
Reputation: 14217
arr.map(_.split("\\*")).count(i => i.headOption.exists(_.contains("AB")))
count
by contains
function with first element and use Option
to handle None
.
Upvotes: 0