文本挖掘实例

本文介绍了一种在Hadoop集群环境中,利用Lucene进行文本挖掘的实践。首先介绍了开发环境,包括系统、IDE和Java版本。接着详细列出了所需的jar包,包括lucene和paoding-analysis等。在集群环境部分,描述了节点配置、软件版本和相关工具如Hadoop、Mahout和Pig。然后是数据准备和开发步骤,重点讲解了如何解决小文件问题,自定义CombineFileInputFormat和RecordReader以提高处理效率。最后展示了MapReduce程序的实现过程,以及如何生成cbayes模型和使用Pig进行数据处理,以确定用户最感兴趣的分类。
摘要由CSDN通过智能技术生成

一、开发环境:

1、系统:WIN7

2、IDE:Eclipse

3、Java:jdk1.6


二、所需jar包

1、lucene-core-3.1.0.jar

2、paoding-analysis.jar

3、数据词典 dic


三、集群环境

1、节点:Master(1),Slave(2)

2、系统:RedHat 6.2

3、JDK:jdk1.6

4、Hadoop: Hadoop1.1.2

5、Mahout: Mahout0.6

6、pig: pig0.11


四、数据准备

1、18.7M,8000+个模型文件

2、19.2M,9000+个测试文件


五、开发步骤

(一)、购建cbayes模型

1、模型文件由8000多个小文件组成,若用MapReduce默认的FileInputFormat读取时,将产生至少8000+个map任务,这样效率将非常低,为了处理小文件的问题,需要自定义FileInputFormat并extends CombineFileInputFormat (将多个小文件组合生成切片).

自定义的CombineFileInputFormat 和 RecordReader 代码如下:

1)、自定义的CombineFileInputFormat 

package fileInputFormat;
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileRecordReader;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;


public class MyFileInputFormat extends CombineFileInputFormat<Text, Text>{
@Override
public RecordReader<Text,Text> createRecordReader(InputSplit split,TaskAttemptContext context) throws IOException {
CombineFileRecordReader<Text, Text> recordReader =new CombineFileRecordReader<Text, Text>((CombineFileSplit)split, context, MyFileRecordReader.class);

//返回自定义的RecordReader 
return recordReader;
}
//要求一个文件必须在一个切片中,一个切片可以包含多个文件
@Override
protected boolean isSplitable(JobContext context, Path file) {
return false;
}
}

2)、自定义的RecordReader

package fileInputFormat;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.LineRecordReader;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.hadoop.util.ReflectionUtils;


public class MyFileRecordReader extends RecordReader<Text,Text>{
private Text currentKey = new Text();      // 当前的Key
private Text currentValue = new Text();    // 当前的Value
private Configuration conf;                // 任务信息
private boolean processed;              // 记录当前文件是否已经读取
private CombineFileSplit split;         //待处理的任务切片
private int totalLength;       //切片包含的文件数量
private int index;                                 //当前文件在split中的索引
private float currentProgress = 0;    //当前的处理进度

public MyFileRecordReader(CombineFileSplit split, TaskAttemptContext context, Integer index) throws IOException {
       super();
       this.split = split;
       this.index = index; // 当前要处理的小文件Block在CombineFileSplit中的索引
       this.conf = context.getConfiguration();
       this.totalLength = split.getPaths().length;
       this.processed = false;
}
@Override
public void close() throws IOException {
}
@Override
public Text getCurrentKey() throws IOException, InterruptedException {
// TODO Auto-generated method stub
return currentKey;
}
@Override
public Text  getCurrentValue() throws IOException, InterruptedException {
// TODO Auto-generated method stub
return currentValue;
}
@Override
public float getProgress() throws IOException, InterruptedException {
if (index >= 0 &&

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的文本挖掘实例,使用Python实现: 1. 导入必要的库 ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import re import nltk from nltk.corpus import stopwords ``` 2. 导入数据 ```python df = pd.read_csv('news.csv') ``` 3. 数据清洗 ```python # 删除缺失值 df.dropna(inplace=True) # 去除文本中的标符号和数字 df['text'] = df['text'].apply(lambda x: re.sub('[^a-zA-Z]', ' ', x)) # 转换为小写 df['text'] = df['text'].apply(lambda x: x.lower()) # 分词 nltk.download('punkt') df['text'] = df['text'].apply(lambda x: nltk.word_tokenize(x)) # 去除停用词 nltk.download('stopwords') stop_words = set(stopwords.words('english')) df['text'] = df['text'].apply(lambda x: [word for word in x if word not in stop_words]) ``` 4. 词频统计 ```python # 将分词后的文本转换为字符串 df['text'] = df['text'].apply(lambda x: ' '.join(x)) # 统计词频 from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features=1000) X = cv.fit_transform(df['text']).toarray() ``` 5. 可视化 ```python # 绘制词云图 from wordcloud import WordCloud cloud = WordCloud(width=800, height=600, background_color='white').generate(' '.join(df['text'])) plt.figure(figsize=(8, 6), facecolor=None) plt.imshow(cloud) plt.axis("off") plt.tight_layout(pad=0) plt.show() # 绘制柱状图 freq_words = pd.DataFrame(X, columns=cv.get_feature_names()) top_words = freq_words.sum().sort_values(ascending=False)[:20] sns.barplot(x=top_words.values, y=top_words.index) plt.show() ``` 以上是一个简单的文本挖掘实例,主要包括数据清洗、词频统计和可视化等步骤。在实践中,还可以使用更复杂的技术和模型来进行文本挖掘,例如情感分析、主题建模等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值