Scala:值拆分不是char的成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21861532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: value split is not a member of char
提问by Brigitte
I am trying to write word count program in Scala. I'm using a string "file":
我正在尝试在 Scala 中编写字数统计程序。我正在使用一个字符串"file":
file.map( _.split(" ")).flatMap(word => (word, 1)).reduceByKey( _ + _ )
It is keep saying that:
一直在说:
value split is not a member of Char
value split 不是 Char 的成员
Can't figure out how to solve it!
想不通怎么解决!
回答by Dave Swartz
When you call mapon a Stringit is wrapped with WrappedStringwhich extends AbstractSeq[Char]. Therefore, when you call mapit is as if you are doing so on a Seqof Charnot a Seqof String.
当您调用mapa 时,String它被包裹在WrappedStringwhich extends 中AbstractSeq[Char]。因此,当您调用map它时,就好像您是在 a Seqof Charnot a Seqof上这样做一样String。
See the link below for the code https://github.com/scala/scala/blob/v2.10.2/src/library/scala/collection/immutable/WrappedString.scala
The code below splits by whitespace and returns the size, a word counter.
下面的代码按空格分割并返回大小,一个字计数器。
val file = "Some test data"
file.split("\s+").size
To get a count of the number of times each word in the string appears.
获取字符串中每个单词出现的次数的计数。
val file = "Some test data test"
println(file.split("\s+").toList.groupBy(w => w).mapValues(_.length))
回答by Brigitte
I found out that the code is perfect! Just because I was running it on Spark, the answer was kept in lazy RDD file that I needed to collect it somehow. Therefore, I saved it to a text file and problem solved! Here is the code:
我发现代码是完美的!仅仅因为我在 Spark 上运行它,答案就保存在我需要以某种方式收集它的惰性 RDD 文件中。因此,我将其保存到文本文件中,问题解决了!这是代码:
file.flatMap(line=>line.split(" ")).map(w=>(w,1)).reduceByKey(+).saveAsTextFile("OUT.txt")
file.flatMap(line=>line.split(" ")).map(w=>(w,1)).reduceByKey( +).saveAsTextFile("OUT.txt")
Thanks.
谢谢。

![Scala: List[Future] to Future[List] 忽略失败的期货](/res/img/loading.gif)