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 行に 1 単語が含まれます)
  • 行末をなくす ( cr, lf または crlf)
  • 単語を小文字にする
  • 単語の増分カウント
  • アルファベット順にソートされた各単語とその数を出力します

ティア

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 に答える