【问题标题】:How to count all the words in a textfile with multiple space characters如何计算具有多个空格字符的文本文件中的所有单词
【发布时间】:2019-07-03 20:19:29
【问题描述】:

我正在尝试编写一个计算 Pascal 文本文件中所有单词的程序。我希望它处理多个空格字符,但我不知道该怎么做。

我尝试添加一个布尔函数Space来判断一个字符是否为空格然后做

while not eof(file) do
begin    
  read(file,char);
  words:=words+1;
  if Space(char) then
    while Space(char) do
      words:=words;

但这不起作用,基本上只是总结了我(可能是坏的)关于程序应该是什么样子的想法。有什么想法吗?

【问题讨论】:

    标签: delphi text-files pascal lazarus word


    【解决方案1】:

    基本上,正如 Tom 在他的回答中所概述的那样,您需要一个具有 In_A_Word 和 Not_In_A_Word 两种状态的状态机,然后在您的状态从 Not_In_A_Word 变为 In_A_Word 时进行计数。

    类似于(伪代码):

    var
      InWord: Boolean;
      Ch: Char;
    begin
      InWord := False;
      while not eof(file) do begin    
        read(file, Ch);
        if Ch in ['A'..'Z', 'a'..'z'] then begin
          if not InWord then begin
            InWord := True;
            Words := Words + 1;
          end;
        end else
          InWord := False
      end;
    end;
    

    【讨论】:

    • 不适用于“Jag äter mycket bönor”。 (4 个字)或“他是一只打击犯罪的狗”。 (5 个字)或“太好了!” (2 个字)。我认为这就是为什么你不应该将算法基于“X 是一个字母”,而是“X 是空白”。
    • 它适用于word 的某些特定定义:P
    • 太棒了,这个想法经过一些小的修改帮助我做到了!非常感谢。
    • @Andreas "Jag äter mera morötter" ;)
    【解决方案2】:

    使用boolean 变量来指示您是否正在处理一个单词。

    first only非空格字符上设置true(并增加计数器)。

    在空格字符上设置false

    【讨论】:

    • 这确实是最简单形式的一般概念。但总是有边缘情况。例如,“I saw a cat/dog.”中有多少个单词?当然,由于“打击犯罪的狗”或“爱狗的家庭”(或“7-脱氢胆固醇”),一般不能将标点符号视为空格。
    • 加上一个用于基于空格测试而不是字母测试的算法。
    • 当然:输入必须格式正确。如果空格不跟随标点符号,使用普通人类产生的文本将失败。并且基于语言空间,当连字符应该组合成一个单词时,可能会被非法使用。
    【解决方案3】:

    另一种方法是读取一个字符串中的整个文件,然后使用以下步骤计算单词:

    {$mode objfpc}
    uses sysutils; 
    
    var
      fullstr: string = 'this is   a     test  string. '; 
      ch: char;
      count: integer=0; 
    
    begin 
      {trim string- remove spaces at beginning and end: }
      fullstr:= trim(fullstr); 
    
      {replace all double spaces with single: }
      while pos('  ', fullstr) > 0 do 
        fullstr := stringreplace(fullstr, '  ', ' ', [rfReplaceAll, rfIgnoreCase]); 
    
      {count spaces: }
      for ch in fullstr do
        if ch=' ' then 
          count += 1; 
    
      {add one to get number of words: }
      writeln('Number of words: ',count+1); 
    end.
    

    上面代码中的cmets解释了步骤。

    输出:

    Number of words: 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多