Problem
【问题描述】
打开一英文文章(保存在一个现有文件in.txt中),为该文件生成词汇表(存到另一个文件out.txt中),要求词汇表中的单词以字典序由小到大存放(只由连续字母组成,且全为小写字母,不重复)。
假设:
1、该文章有可能没有经过排版,格式有可能杂乱无章,也有可能没有写完整。
2、文章中的单词个数不超过1000个,每个单词的长度不超过50个字母。
【输入形式】
保存英文文章的文件in.txt位于当前目录下。
【输出形式】
将生成的词汇表以字典序由小到大输出到当前目录下的文件out.txt中,每个单词单独占一行。
【样例输入1】
假设文件in.txt内容为:
There are two versions of the international standards for C.
The first version was ratified in 1989 by the American National
Standards Institue (ANSI) C standard committee.It is often
referred as ANSI C or C89. The secand C standard was completed
in 1999. This standard is commonly referred to as C99. C99 is a
milestone in C's evolution into a viable programming language
for numerical and scientific computing.
【样例输出1】
文件out.txt中的词汇表应为:
a
american
and
ansi
are
as
by
c
committee
commonly
completed
computing
evolution
first
for
in
institue
international
into
is
it
language
milestone
national
numerical
of
often
or
programming
ratified
referred
s
scientific
secand
standard
standards
the
there
this
to
two
version
versions
viable
was
【样例输入2】
假设文件in.txt内容为:
There are two versions of the international standards for
【样例输出2】
文件out.txt中的词汇表应为:
are
for
international
of
standards
the
there
two
versions
【样例说明】
将in.txt中出现的所有由字母组成的单词(出现的单个字母也作为单词)全部转换成小写后,按照字典序输出到文件out.txt中(每个单词独占一行,重复出现的只输出一次)。
注意:样例2中in.txt文件内容还不完整,单词for后没有任何字符。
【评分标准】本题要求为指定的文件编写单词索引。
import java.io.*;
import java.util.*;
public class everydayjava {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("in.txt"));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line).append(" ");
}
reader.close();
String[] words = content.toString().toLowerCase().split("\\P{L}+");
Set<String> uniqueWords = new TreeSet<>(Arrays.asList(words));
BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
for (String word : uniqueWords) {
writer.write(word);
writer.newLine();
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
其中,split("\\P{L}+")意为匹配非字母字符并分割
而去重排序我用到了TreeSet,可以确保单词唯一且按字典序排序。