用scala写一段wordcount
时间: 2024-03-22 21:37:49 浏览: 11
以下是一个简单的使用Scala实现Word Count的程序:
```scala
import org.apache.flink.api.scala._
object WordCount {
def main(args: Array[String]): Unit = {
// 创建一个执行环境
val env = ExecutionEnvironment.getExecutionEnvironment
// 读取文本文件并将每行拆分为单词
val input = env.readTextFile("path/to/textfile")
val words = input.flatMap(line => line.split("\\s+"))
// 计算每个单词的出现次数
val counts = words.map(word => (word, 1))
.groupBy(0)
.sum(1)
// 打印结果
counts.print()
}
}
```
运行以上代码,可以读取指定路径下的文本文件,对文件中的每个单词进行计数,并输出每个单词出现的次数。
相关问题
用Scala 写一段flink 连接mysql的代码
以下是一个简单的使用Scala连接MySQL数据库,并使用Flink进行数据操作的程序:
```scala
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import org.apache.flink.api.scala._
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction
object MySQLSink {
def main(args: Array[String]): Unit = {
// 创建一个执行环境
val env = StreamExecutionEnvironment.getExecutionEnvironment
// 读取数据源
val input = env.fromElements(("foo", 1), ("bar", 2), ("baz", 3))
// 将数据插入到MySQL数据库中
input.addSink(new MySQLSinkFunction)
// 执行计算并输出结果
env.execute("MySQL Sink Example")
}
class MySQLSinkFunction extends RichSinkFunction[(String, Int)] {
var connection: Connection = _
var preparedStatement: PreparedStatement = _
override def open(parameters: Configuration): Unit = {
// 连接MySQL数据库
Class.forName("com.mysql.jdbc.Driver")
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password")
// 创建预编译语句
preparedStatement = connection.prepareStatement("INSERT INTO wordcount (word, count) VALUES (?, ?)")
}
override def invoke(value: (String, Int), context: SinkFunction.Context[_]): Unit = {
// 将数据插入到MySQL数据库中
preparedStatement.setString(1, value._1)
preparedStatement.setInt(2, value._2)
preparedStatement.executeUpdate()
}
override def close(): Unit = {
// 关闭连接
if (preparedStatement != null) preparedStatement.close()
if (connection != null) connection.close()
}
}
}
```
运行以上代码,可以将数据源中的数据插入到MySQL数据库的`wordcount`表中。需要注意的是,上述代码中的数据库连接信息需要根据实际情况进行修改。
scala wordcount 词频统计
Scala是一种基于JVM的编程语言,可以用来实现词频统计(wordcount)功能。词频统计是指对一段文本中出现的单词进行统计,得出每个单词出现的次数,从而得出单词的词频。在Scala中,可以使用Map集合来实现词频统计功能,具体实现方法可以参考Scala官方文档或相关教程。