查找任意一英文文档,统计其单词出现次数

import java.io.*;
import java.util.*;

class Demo {

    public static void main(String[] args) {
        File f = new File("F:\\tx.txt");
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(f));
            bw = new BufferedWriter(new FileWriter("cha.txt"));
            String line = null;
            Map<String,Integer> map = new TreeMap<String,Integer>();
            while ((line = br.readLine()) != null) {
                // 正则表达式(获取)
                String reg = "\\b[a-zA-Z]+\\b";
                // 将正则表达式封装为对象
                Pattern p = Pattern.compile(reg);
                // 将正则表达式对象和要作用的字符串匹配
                Matcher m = p.matcher(line.toLowerCase());//全部变为小写
                int temp =0;
                while (m.find()) {
                    //System.out.println(m.group());
                    //将单词存入treemap,值为其出现次数
                    Integer value = map.get(m.group());
                    if (value != null)
                        temp = value;
                    temp++;
                    map.put(m.group(), temp);
                    temp = 0;
                }
                bw.write(map.toString());
            }
            System.out.println(map);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
                if (bw != null)
                    bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于Python构建倒排索引并实现关键字搜索的代码: ```python import os import re import json # 读取文件,返回文件内容 def read_file(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() return content # 处理文件内容,返回单词列表 def process_content(content): # 将所有非字母字符替换为空格,转换为小写 content = re.sub(r'[^a-zA-Z]', ' ', content).lower() # 将连续多个空格替换为一个空格 content = re.sub(r'\s+', ' ', content) # 将字符串按空格分割为单词列表 words = content.strip().split(' ') return words # 构建倒排索引 def build_index(dir_path): # 创建空字典 index = {} # 遍历目录下的所有文件 for filename in os.listdir(dir_path): file_path = os.path.join(dir_path, filename) if os.path.isfile(file_path): # 读取文件内容 content = read_file(file_path) # 处理文件内容,得到单词列表 words = process_content(content) # 遍历单词列表,将每个单词添加到倒排索引中 for word in set(words): if word not in index: index[word] = [] index[word].append(filename) return index # 保存倒排索引 def save_index(index, file_path): with open(file_path, 'w', encoding='utf-8') as f: json.dump(index, f) # 加载倒排索引 def load_index(file_path): with open(file_path, 'r', encoding='utf-8') as f: index = json.load(f) return index # 查找包含指定单词的文件 def search_word(word, index): if word in index: return index[word] else: return [] # 主函数 def main(): dir_path = 'data' # 数据目录 index_file = 'index.json' # 倒排索引文件 # 如果倒排索引文件不存在,则创建 if not os.path.exists(index_file): # 构建倒排索引 index = build_index(dir_path) # 保存倒排索引 save_index(index, index_file) else: # 加载倒排索引 index = load_index(index_file) # 输入关键字 word = input('请输入关键字:') # 查找包含指定单词的文件 files = search_word(word, index) # 打印结果 print('包含关键字“{}”的文件有:'.format(word)) for file in files: print(file) if __name__ == '__main__': main() ``` 注意事项: 1. 本代码需要在Python3环境下运行。 2. 数据目录中的每个文件应该是一个文本文件,文件名可以是任意字符串。 3. 倒排索引文件使用JSON格式保存,文件名默认为“index.json”,可以在代码中修改。 4. 运行代码后,会提示输入关键字,输入后会输出包含该关键字的文件名。如果没有包含该关键字的文件,则输出空列表。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值