F# 统计一段英文文章中不同单词出现的次数

本文介绍了一个使用F#语言实现的简单应用,通过构建二叉树来统计英文文章中各单词出现的频率。该程序利用.NET的File.ReadAllText读取文件内容,并以中序遍历的方式输出每个单词及其对应的出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

统计一段英文文章中不同单词出现的次数,用F#写着玩玩,纯属娱乐!嘿嘿

使用二叉树,中序遍历输出;调用.NET 的File.ReadAllText读取文件

 

module node
//二叉树 ,Node为节点,Empty为空节点
type Tree = Empty | Node of Tree * string * int * Tree

//中序遍历
letrec printTree t=
match t with
| Empty -> printfn ""
| Node(l,data,num,r) as n ->
printTree l
printfn
"%s ---次数是----- %d" data num
printTree r
 
//递归插入节点,节点为空则插入新节点,若比节点数据data大,则插入其右子节点,若比他小,则插入其左节点
//若等于,则将节点的num加一,表明这个单词又出现一次
letrec insert1 = function
| x ,n, Empty -> Node(Empty,x,1,Empty)
| x ,n, Node(l ,data,num,r) ->
if x <data then Node(insert(x,1,l),data,num,r)
elif x > data
then Node( l ,data,num,insert(x,1,r))
else Node(l,data,num+1,r)

 

open System
open System.IO
[<EntryPoint
>]
let main (args : string[]) =
let reader =File.ReadAllText("D:\\s.txt")
//以空格分割文件中的内容,得到单词string数组
let strings = reader.Split('')
//定义可变的root
letmutable root = node.Empty
//遍历所有单词,构造二叉树
for s in strings do
root
<- node.insert1 (s,1,root)
 //中序遍历,输出统计内容
node.printTree root
0

转载于:https://www.cnblogs.com/xiwang/archive/2011/06/23/xiwang.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值