簡體   English   中英

使用MapReduce刪除包含特定單詞的整個句子

[英]Remove an entire sentence containing a specific word with MapReduce

我正在學習MapReduce,我想讀取一個輸入文件(逐句),並且只有在不包含單詞“snake”時才將每個句子寫入輸出文件。

例如輸入文件:

This is my first sentence. This is my first sentence.
This is my first sentence.

The snake is an animal. This is the second sentence. This is my third sentence.

Another sentence. Another sentence with snake.

那么輸出文件應該是:

This is my first sentence. This is my first sentence.
This is my first sentence.

This is the second sentence. This is my third sentence.

Another sentence.

為此,我在map方法中檢查句子( value )是否包含單詞snake。 如果句子不包含蛇詞,那么我在context寫下該句子。

另外,我將reducer任務的數量設置為0,否則在輸出文件中我以隨機順序得到句子(例如第一個句子,然后是第三個句子,然后是第二個句子,依此類推)。

我的代碼使用蛇詞正確地過濾了句子,但問題是它將每個句子寫成一個新行,如下所示:

This is my first sentence. 
 This is my first sentence. 

This is my first sentence. 
 This is the second sentence. 
 This is my third sentence. 


Another sentence. 

. 

只有當該句子出現在輸入文本的新行中時,如何才能在新行中編寫句子? 以下是我的代碼:

public class RemoveSentence {

    public static class SentenceMapper extends Mapper<Object, Text, Text, NullWritable>{

        private Text removeWord = new Text ("snake");

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            if (!value.toString().contains(removeWord.toString())) {
                Text currentSentence = new Text(value.toString()+". ");
                context.write(currentSentence, NullWritable.get());
            }
        }
    }


    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("textinputformat.record.delimiter", ".");

        Job job = Job.getInstance(conf, "remove sentence");
        job.setJarByClass(RemoveSentence.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setMapperClass(SentenceMapper.class);
        job.setNumReduceTasks(0);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

另一個解決方案說應該足以設置context.write(word, null); 但在我的情況下沒有奏效。

另一個問題與conf.set("textinputformat.record.delimiter", "."); 好吧,這就是我如何定義句子之間的分隔符,因此有時輸出文件中的句子以空格開頭(例如,第二個This is my first sentence. )。 作為替代方案,我試圖將它設置為conf.set("textinputformat.record.delimiter", ". "); (在完全停止后有空格)但是這樣Java應用程序不會在輸出文件中寫入所有句子。

你非常接近解決這個問題。 想想你的MapReduce程序是如何工作的。 你的map方法將每個句子用“。”分隔。 (如您所知,默認為換行符)作為新值,然后將其寫入文件。 您需要一個屬性,在每次map()調用后禁用寫入換行符。 我不確定,但我不認為這樣的財產存在。

一種解決方法是讓它正常處理。 示例記錄將是:

This is first sentence. This is second snake. This is last.

找到“snake”這個詞,如果找到,請在上一個“。”之后立即刪除所有內容。 到下一個 ”。” 打包新String並將其寫入上下文。

當然,如果你能找到一種在map()調用之后禁用換行的方法,那么這將是最簡單的方法。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM