计数在一个文件中的单词数 [英] Counting number of words in a file

查看:166
本文介绍了计数在一个文件中的单词数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题计数在一个文件中的字的数量。我正在采取的方法是,当我看到一个空格或一个换行符后来我知道算一个字。

现在的问题是,如果我有段落之间的多条线路,然后我最终计数他们作为的话也。如果你看一下READFILE()方法,你可以看到我在做什么。

你能帮助我,引导我在正确的方向上如何解决这一问题?

例输入文件(包括空行):

 字字字
一字一句

字字字
 

解决方案

我会改变你的做法有点。首先,我会用一个的BufferedReader 来读取行由行中使用文件fil​​e 的readLine()。然后分裂空格每行使用 String.split(\\ S),然后用这个数组的大小,看看有多少话是在该行。要获取的字符数,你可以要不是看在每一行的每个拆分单词或大小(具体取决于您是否要计算为空白字符)。

I'm having a problem counting the number of words in a file. The approach that I am taking is when I see a space or a newLine then I know to count a word.

The problem is that if I have multiple lines between paragraphs then I ended up counting them as words also. If you look at the readFile() method you can see what I am doing.

Could you help me out and guide me in the right direction on how to fix this?

Example input file (including a blank line):

word word word
word word

word word word

解决方案

I would change your approach a bit. First, I would use a BufferedReader to read the file file in line-by-line using readLine(). Then split each line on whitespace using String.split("\\s") and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).

这篇关于计数在一个文件中的单词数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆