大数据分词功能--提取文章中关键字

大数据分词功能--提取文章中关键字

废话不多说,直接上代码

1、由于分词IKAnalyzer包可能需要外网才能获取,经多处查找资料需要在maven工程中pom.xml需要加入

        <dependency>
            <groupId>com.jianggujin</groupId>
            <artifactId>IKAnalyzer-lucene</artifactId>
            <version>8.0.0</version>
        </dependency>

2、导入分词工具包:

import org.apache.lucene.analysis.TokenStream;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

3、代码:

		String keyWord = "";
        //keyWord = executeExtractSql(conn,returnCol,resourceObj,conidtion);//获取字符串
        Map rowData = new HashMap();
        keyWord = "雨是最寻常的,一下就是三两天。可别恼。看,像牛毛,像花针,像细丝,密密地斜织着,人家屋顶上全笼着一层薄烟。树叶儿却绿得发亮,小草儿也青得逼你的眼。傍晚时候,上灯了,一点点黄晕的光,烘托出一片安静而和平的夜。在乡下,小路上,石桥边,有撑起伞慢慢走着的人,地里还有工作的农民,披着蓑戴着笠。他们的房屋,稀稀疏疏的在雨里静默着。" ;
        String [] keywords = getKeyWords(keyWord);
        keyWord = "";
        for(int i=0; i<keywords.length; i++){
            keyWord += keywords[i] + ",";
            System.out.println(keywords[i]);
        }
		return keyWord;//返回拼接后的高频率词
		
 /** 获取关键字个数 */
    private final static Integer NUM=5;
    /** 截取关键字在几个单词以上的数量 */
    private final static Integer QUANTITY=1;
    /**
     * 传入String类型的文章,智能提取单词放入list中
     * @param article
     * @param a
     * @return
     * @throws IOException
     */
    private static List<String> extract(String article,Integer a)throws IOException{
        List<String> list =new ArrayList<String>(); //定义一个list来接收将要截取出来单词
        IKAnalyzer analyzer = new IKAnalyzer(); //初始化IKAnalyzer
        analyzer.setUseSmart(true); //将IKAnalyzer设置成智能截取
        TokenStream tokenStream= //调用tokenStream方法(读取文章的字符流)
                analyzer.tokenStream("", new StringReader(article));
        tokenStream.reset();
        while (tokenStream.incrementToken()) { //循环获得截取出来的单词
            CharTermAttribute charTermAttribute = //转换为char类型
                    tokenStream.getAttribute(CharTermAttribute.class);
            String keWord= charTermAttribute.toString(); //转换为String类型
            if (keWord.length()>a) { //判断截取关键字在几个单词以上的数量(默认为2个单词以上)
                list.add(keWord); //将最终获得的单词放入list集合中
            }
        }
        tokenStream.end();
        tokenStream.close();
        return list;
    }
    /**
     * 将list中的集合转换成Map中的key,value为数量默认为1
     * @param list
     * @return
     */
    private static Map<String, Integer> list2Map(List<String> list){
        Map<String, Integer> map=new HashMap<String, Integer>();
        for(String key:list){ //循环获得的List集合
            if (list.contains(key)) { //判断这个集合中是否存在该字符串
                map.put(key, map.get(key) == null ? 1 : map.get(key)+1);
            } //将集中获得的字符串放在map的key键上
        } //并计算其value是否有值,如有则+1操作
        return map;
    }
    /**
     * 提取关键字方法
     * @param article
     * @param a
     * @param n
     * @return
     * @throws IOException
     */
    public static String[] getKeyWords(String article,Integer a,Integer n) throws IOException {
        List<String> keyWordsList= extract(article,a); //调用提取单词方法
        Map<String, Integer> map=list2Map(keyWordsList); //list转map并计次数
        //使用Collections的比较方法进行对map中value的排序
        ArrayList<Entry<String, Integer>> list = new ArrayList<Entry<String,Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue() - o1.getValue());
            }
        });
        if (list.size()<n) n=list.size(); //排序后的长度,以免获得到null的字符
        String[] keyWords=new String[n]; //设置将要输出的关键字数组空间
        for(int i=0; i< list.size(); i++) { //循环排序后的数组
            if (i<n) { //判断个数
                keyWords[i]=list.get(i).getKey(); //设置关键字进入数组
            }
        }
        return keyWords;
    }
    /**
     *
     * @param article
     * @return
     * @throws IOException
     */
    public static String[] getKeyWords(String article){
        try{
            return getKeyWords(article,QUANTITY,NUM);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

参考文章链接

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Python实现英文大数据txt文本TF-IDF提取关键的代码: ```python import os import math import string from collections import Counter # 读取文本文件 def read_file(filename): with open(filename, 'r', encoding='utf-8') as f: text = f.read() return text # 分词 def tokenize(text): words = text.lower().split() # 去除标点符号 words = [word.strip(string.punctuation) for word in words] # 去除数字和单个字母 words = [word for word in words if not any(c.isdigit() for c in word) and len(word) > 1] return words # 计算单出现次数 def count_words(words): word_counts = Counter(words) return word_counts # 计算单在文档出现的频率 def compute_word_frequency(word_counts): total_count = sum(word_counts.values()) word_freqs = {word: count/total_count for word, count in word_counts.items()} return word_freqs # 计算单在文档集合出现的文档数量 def compute_document_frequency(word, documents): count = sum(1 for document in documents if word in document) return count # 计算单的逆文档频率 def compute_inverse_document_frequency(word, documents): N = len(documents) df = compute_document_frequency(word, documents) idf = math.log(N/df) return idf # 计算TF-IDF def compute_tf_idf(word, words, documents): tf = words[word] idf = compute_inverse_document_frequency(word, documents) tf_idf = tf * idf return tf_idf # 提取关键 def extract_keywords(filename, num_keywords=10): # 读取文本文件 text = read_file(filename) # 分词 words = tokenize(text) # 计算单出现次数 word_counts = count_words(words) # 计算单在文档出现的频率 word_freqs = compute_word_frequency(word_counts) # 计算TF-IDF documents = [words] tf_idfs = {word: compute_tf_idf(word, word_freqs, documents) for word in word_counts.keys()} # 获取前num_keywords个TF-IDF最高的关键 keywords = sorted(tf_idfs.items(), key=lambda x: x[1], reverse=True)[:num_keywords] return [keyword[0] for keyword in keywords] # 测试 filename = 'data.txt' keywords = extract_keywords(filename, num_keywords=10) print(keywords) ``` 其,`read_file`函数用于读取文本文件,`tokenize`函数用于对文本进行分词,`count_words`函数用于统计单出现次数,`compute_word_frequency`函数用于计算单在文档出现的频率,`compute_document_frequency`函数用于计算单在文档集合出现的文档数量,`compute_inverse_document_frequency`函数用于计算单的逆文档频率,`compute_tf_idf`函数用于计算TF-IDF,`extract_keywords`函数用于提取关键。 在测试时,将要提取关键文本文件路径传入`extract_keywords`函数,同时可以指定要提取的关键数量。运行后,将会返回一个关键列表,其包含了TF-IDF值最高的前num_keywords个关键

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值