hen*_*enq 1 string associative-array scala
我看到很多Scala教程,其中包含一些示例,例如招聘遍历或解决数学问题.在我的日常编程生活中,我感觉我的大部分编码时间都花在了字符串操作,数据库查询和日期操作等普通任务上.有兴趣举例说明以下perl脚本的Scala版本吗?
#!/usr/bin/perl
use strict;
#opens a file with on each line one word and counts the number of occurrences
# of each word, case insensitive
print "Enter the name of your file, ie myfile.txt:\n";
my $val = <STDIN>;
chomp ($val);
open (HNDL, "$val") || die "wrong filename";
my %count = ();
while ($val = <HNDL>)
{
chomp($val);
$count{lc $val}++;
}
close (HNDL);
print "Number of instances found of:\n";
foreach my $word (sort keys %count) {
print "$word\t: " . $count{$word} . " \n";
}
Run Code Online (Sandbox Code Playgroud)
综上所述:
TIA
dre*_*xin 10
像这样的简单字数可以写成如下:
import io.Source
import java.io.FileNotFoundException
object WC {
def main(args: Array[String]) {
println("Enter the name of your file, ie myfile.txt:")
val fileName = readLine
val words = try {
Source.fromFile(fileName).getLines.toSeq.map(_.toLowerCase.trim)
} catch {
case e: FileNotFoundException =>
sys.error("No file named %s found".format(fileName))
}
val counts = words.groupBy(identity).mapValues(_.size)
println("Number of instances found of:")
for((word, count) <- counts) println("%s\t%d".format(word, count))
}
}
Run Code Online (Sandbox Code Playgroud)