EverydayJava 单词索引编排

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,可以确保单词唯一且按字典序排序。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XforeverZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值