使用 F# 编写文件处理程序

在本篇文章中,我们将使用 F# 编写一个简单的文件处理程序。该程序将读取一个文本文件,统计文件中每个单词的出现频率,并将结果输出到一个新的文本文件。

环境准备
安装 .NET SDK

首先,确保已安装 .NET SDK。你可以通过以下命令检查是否已经安装:

bash
dotnet --version
如果没有安装,请前往 dotnet官网 下载并安装合适的版本。

创建 F# 项目

创建一个新的 F# 控制台应用程序:

bash

dotnet new console -lang "F#" -o WordFrequencyApp
cd WordFrequencyApp
编写代码

  1. 读取文件
    我们将创建一个函数来读取文件内容,并将每一行分解为单词列表。这里使用 System.IO 命名空间来读取文件内容。

fsharp

open System
open System.IO

let readFile filePath =
try
let lines = File.ReadAllLines(filePath)
Some lines
with
| :? FileNotFoundException ->
printfn "File not found."
None
| ex ->
printfn "Error: %s" ex.Message
None
2. 统计单词频率
接下来,我们将定义一个函数来统计文本中每个单词的出现频率。我们会将文件内容拆分成单词,并使用字典来记录每个单词的频率。

fsharp

let countWordFrequency (lines: string[]) =
let wordCount =
lines
|> Array.collect (fun line -> line.Split([| ' '; '\t'; ','; '.'; '!'|], StringSplitOptions.RemoveEmptyEntries))
|> Array.map (fun word -> word.ToLower())
|> Array.fold (fun dict word ->
if dict.ContainsKey(word) then
dict.[word] <- dict.[word] + 1
else
dict.[word] <- 1
dict
) (System.Collections.Generic.Dictionary<string, int>())
wordCount
3. 输出结果到文件
我们将创建一个函数来将统计的结果输出到一个新的文本文件中。

fsharp

let writeResultsToFile wordCount outputFilePath =
try
use writer = new StreamWriter(outputFilePath)
wordCount
|> Seq.sortByDescending snd
|> Seq.iter (fun (word, count) -> writer.WriteLine($"{word}: {count}"))
printfn "Results written to %s" outputFilePath
with
| ex -> printfn "Error: %s" ex.Message
4. 主程序
将上述函数组合起来,并实现主程序的逻辑来读取输入文件、统计单词频率并输出结果。

fsharp

[]
let main argv =
let inputFile = "input.txt" // 输入文件路径
let outputFile = "output.txt" // 输出文件路径

match readFile inputFile with
| Some lines ->
    let wordCount = countWordFrequency lines
    writeResultsToFile wordCount outputFile
| None -> 
    printfn "Unable to process the file."

0  // 返回值,表示程序成功执行

代码解析
readFile 函数:

使用 File.ReadAllLines 读取文件内容,将文件的每一行作为字符串数组返回。
如果文件不存在或其他错误,捕获异常并打印错误信息。
countWordFrequency 函数:

将每一行拆分成单词,并去掉标点符号和空格。
使用 Dictionary 存储每个单词的出现频率,Array.fold 用来遍历所有单词并更新字典。
writeResultsToFile 函数:

使用 StreamWriter 将结果写入到指定的输出文件中。
按照频率降序排序后输出每个单词及其频率。
主程序:

读取输入文件,调用上述函数完成单词统计,并将结果输出到文件中。
测试程序
创建一个名为 input.txt 的文件,内容如下:

r

Hello world! This is a test.
Hello F# programming language.
F# is functional.
运行程序:

bash

dotnet run
查看生成的 output.txt 文件,内容应该如下:

makefile

hello: 2
f#: 2
world: 1
this: 1
is: 1
a: 1
test: 1更多内容访问ttocr.com或联系1436423940
programming: 1
language: 1
functional: 1

posted @   ttocr、com  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示