zoukankan      html  css  js  c++  java
  • F# 统计一段英文文章中不同单词出现的次数

    统计一段英文文章中不同单词出现的次数,用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
    作者:墨梅
    欢迎任何形式的转载,但请务必注明出处。
  • 相关阅读:
    P4720 【模板】扩展卢卡斯
    P3211 [HNOI2011]XOR和路径
    ZOJ 3329 One Person Game
    CF817F MEX Queries
    P3239 [HNOI2015]亚瑟王
    P3412 仓鼠找sugar II
    P4111 [HEOI2015]小Z的房间
    P4008 [NOI2003]文本编辑器
    CF451E Devu and Flowers
    P3975 [TJOI2015]弦论
  • 原文地址:https://www.cnblogs.com/xiwang/p/xiwang.html
Copyright © 2011-2022 走看看