【问题标题】:How to Count the Number of Words in a Text File using Javascript如何使用 Javascript 计算文本文件中的字数
【发布时间】:2015-11-11 21:59:09
【问题描述】:

我在这里有货。

我正在尝试在我的 Web 应用程序 (HTML5) 上集成一项功能,该功能使用户能够使用普通的 HTML 文件输入框选择文本文件,并将所选文本文件中的总字数真实显示给他们-时间。

这是我目前对 Javascript 部分的了解:

<script>
    //function to count words in selected text file
    $(function() {
        $('#upload').change( function(event) {
            var tmppath = URL.createObjectURL(event.target.files[0]); //get temp path of selected file

            //some codes here to read the file selected by the user and store the number of words in a string called total_word 
            $("#display_File_count").text(total_word); //display the number of words in the appropriate span
        });
    });
</script>

这里是 HTML 部分;

<input name="upload" type="file" id="upload" accept="text/plain" accesskey="u">
                <div><span id="display_File_count">0</span> <span> words</span></div> 

当用户点击文件选择器并选择一个文本文件时,脚本应该读取文本文件的内容,计算其中包含的单词数(全部在客户端完成)。

然后在 id 为“display_file_count”的 span 内显示单词的数量。

求求你们,我需要一条出路。

提前致谢。

【问题讨论】:

  • 在空格字符上分割字符串;计算结果数组中的元素个数
  • FileReader API -> 异步加载属性 -> FileReader.readAsText -> String.prototype.split on whitespace -> Array.prototype.length。享受吧。
  • @ElGavilan 我的主要问题是在客户端获取选定的文本文件,而不是真正进行计数。
  • @Marcel W,该线程正在讨论计算文本框内容,这很容易。我需要一种方法来计算所选文本文件中包含的单词,而不会将其提交给服务器。 (因此,在表单提交之前)

标签: javascript jquery html


【解决方案1】:

我会使用 FileReader(记得检查浏览器兼容性 - 因为不是所有浏览器都支持它)

$('#upload').change( function(event) {

    var f = event.target.files[0];
    if (f) {
        var r = new FileReader();

        r.onload = function(e) { 
            var contents = e.target.result;
            var res = contents.split(" "); 
            $("#display_File_count").text(res.length);
        }
        r.readAsText(f);
    }
});

【讨论】:

  • 让我尝试解决您的解决方案。它看起来很有吸引力和积极。谢谢
  • 效果很好。只需稍加修改,我就能让它在 IE 和旧版 FF 上运行。
猜你喜欢
  • 2013-11-21
  • 2017-10-15
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
相关资源
最近更新 更多