1

我看到很多 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";
}

总之:

  • 询问文件名
  • 读取文件(每行包含 1 个字)
  • 取消行尾(cr、lf 或 crlf)
  • 小写单词
  • 单词的增量计数
  • 打印出每个单词,按字母顺序排序,以及它的计数

TIA

4

3 回答 3

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))

  }

}
于 2012-12-29T14:06:49.260 回答
3

如果您想要简洁/紧凑,您可以在 2.10 中:

// Opens a file with one word on each line and counts
// the number of occurrences of each word (case-insensitive)
object WordCount extends App {
  println("Enter the name of your file, e.g. myfile.txt: ")
  val lines = util.Try{ io.Source.fromFile(readLine).getLines().toSeq } getOrElse
    { sys.error("Wrong filename.") }
  println("Number of instances found of:")
  lines.map(_.trim.toLowerCase).toSeq.groupBy(identity).toSeq.
    map{ case (w,ws) => s"$w\t: ${ws.size}" }.sorted.foreach(println)
}
于 2012-12-30T11:52:32.870 回答
1
  val lines : List[String] = List("this is line one" , "this is line 2", "this is line three")

  val linesConcat : String = lines.foldRight("")( (a , b) => a + " "+ b)

  linesConcat.split(" ").groupBy(identity).toList.foreach(p => println(p._1+","+p._2.size))

印刷 :

this,3
is,3
three,1
line,3
2,1
one,1
于 2015-08-07T19:52:39.637 回答