Java去除文件中重复的单词

在学习专业英语的时候,喜欢使用world记录单词对应的中文翻译,
如下图:
这里写图片描述
但是发现会存在重复的单词,于是便想到使用Java中的Map集合的特性完成单词去重的任务。
主要步骤:

1.使用Scanner将文件的每一行读入并保存在字符串中;
2.将字符串拆分成中文和英文两个部分;
3.中文部分作为Map集合的key,英文部分作为相应的value;
4.将Map集合的数据使用printWriter打印流重新写回数据,即可完成单词的去重。

代码示例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Iterator;

public class Main{
    public static void main(String [] args) throws IOException{
        // 处理文件
        File infile = new File("/home/linyimin//DaSi/学习/软件工程.txt");
        // 输出文件
        InputStream in = new FileInputStream(infile);
        File outfile = new File("/home/linyimin//DaSi/学习/软件工程_out.txt");
        FileOutputStream out = new FileOutputStream(outfile);
        // 使用打印流完成向文件写入数据
        PrintWriter tool = new PrintWriter(out);
        // 使用Scanner完成从文件中读取数据
        Scanner cin = new Scanner(in);
        // 一次读取一行
        cin.useDelimiter("\n");

        // 使用HashMap完成去重任务
        Map<String, String> map =  new HashMap<String, String>();
        while(cin.hasNext()){
            String str = cin.next();
            // 将每行数据读入,根据多个空格为特征,切分字符串
            // 中文为Map中的key,对应英文为vaule,存入Map集合中
            String [] str1 = str.split("\\s+", 2);

            if(str1.length > 1){
                map.put(str1[0], str1[1] );
            }           
        }

        // 将Map集合转换成Set集合,Set集合使用Iterator进行迭代输出
        Iterator <Map.Entry<String, String>> iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> m = iter.next();
            String chinese = m.getKey();                // 从Map.Entry对象中取出key值
            String english = m.getValue();              // 从Map.Entry对象中取出value值
            // 使用PrintWriter向文件中写入去重之后的数据
            tool.println(chinese + "                     " + english);

        }
        // 关闭资源
        cin.close();
        in.close();
        tool.close();
    }
}
要判断两个文件的内容重复率,需要进行以下步骤: 1. 将文本内容从文件读取出来 2. 对文本进行处理,例如去除标点符号、空格等,保留单词或短语 3. 将处理后的文本转换成向量表示,可以使用词袋模型(Bag of Words)或TF-IDF等方法 4. 计算两个向量的相似度,可以使用余弦相似度(Cosine Similarity)等方法 下面是一个简单的Java代码示例,用于比较两个文本文件的相似度: ```java import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.text.similarity.CosineSimilarity; public class TextSimilarity { public static void main(String[] args) throws IOException { // 读取文件内容 String file1 = readFile("file1.txt"); String file2 = readFile("file2.txt"); // 处理文本,去除标点符号、空格等 List<String> words1 = Arrays.asList(file1.split("\\W+")).stream() .map(String::toLowerCase) .collect(Collectors.toList()); List<String> words2 = Arrays.asList(file2.split("\\W+")).stream() .map(String::toLowerCase) .collect(Collectors.toList()); // 将文本转换成向量表示 BagOfWords bow = new BagOfWords(); bow.addWords(words1); bow.addWords(words2); double[] vector1 = bow.toVector(words1); double[] vector2 = bow.toVector(words2); // 计算相似度 CosineSimilarity cosine = new CosineSimilarity(); double similarity = cosine.cosine(vector1, vector2); System.out.println("相似度:" + similarity); } private static String readFile(String filename) throws IOException { byte[] bytes = Files.readAllBytes(new File(filename).toPath()); return new String(bytes, StandardCharsets.UTF_8); } } ``` 其,BagOfWords类用于构建词袋模型,实现如下: ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BagOfWords { private List<String> vocabulary; private Map<String, Integer> wordCount; public BagOfWords() { vocabulary = new ArrayList<>(); wordCount = new HashMap<>(); } public void addWords(List<String> words) { for (String word : words) { if (!vocabulary.contains(word)) { vocabulary.add(word); } wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); } } public double[] toVector(List<String> words) { double[] vector = new double[vocabulary.size()]; for (String word : words) { int index = vocabulary.indexOf(word); if (index != -1) { vector[index] += 1.0 / wordCount.get(word); } } return vector; } } ``` 需要注意的是,这种方法对于大型文件和大量重复内容的文件可能会存在性能问题。如果需要比较较大的文件,可以使用流式处理或多线程处理来提高效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值