用Python編寫WordCount程式任務

來源:互聯網
上載者:User

標籤:+=   count   下載   間隔   stream   split()   info   編寫程式   txt   

1. 用Python編寫WordCount程式並提交任務

程式

WordCount

輸入

一個包含大量單詞的文字檔

輸出

檔案中每個單詞及其出現次數(頻數),並按照單詞字母順序排序,每個單詞和其頻數佔一行,單詞和頻數之間有間隔

2.編寫map函數,reduce函數

import sysfor line in sys.stdin:     line=line.strip()     words=line.split()     for word in words:          print ‘%s\t%s‘ % (word,1)from operator import itemgetterimport syscurrent_word=Nonecurrent_count=0word=Nonefor line in sys.stdin:     line=line.strip()     word,count=line.split(‘\t‘,1)     try:          count=int(count)     except ValueError:          continue     if current_word==word:          current_count+=count     else:          if current_word:              print ‘%s\t%s‘ % (current_word,current_count)          current_count=count          current_word=wordif current_word==word:     print ‘%s\t%s‘ % (current_word,current_count)

3.將其許可權作出相應修改

chmod a+x /home/hadoop/wc/mapper.pychmod a+x /home/hadoop/wc/reducer.py

4.本機上測試回合代碼

 

5.查看運行結果

 

2. 用mapreduce 處理氣象資料集

編寫程式求每日最高最低氣溫,區間最高最低氣溫

  1. 氣象資料集為:ftp://ftp.ncdc.noaa.gov/pub/data/noaa
  2. 按學號後三位下載不同年份月份的資料(例如201506110136號同學,就下載2013年以6開頭的資料,看具體資料情況稍有變通)
    wget -D --accept-regex=REGEX -p data -r -c ftp://ftp.ncdc.noaa.gov/pub/data/noaa/2013/6*
  3. 解壓資料集,並儲存在文字檔中
    zcat ftp.ncdc.noaa.gov/pub/data/noaa/2013/6*.gz >qxdatazwt.txt
  4. 對氣象資料格式進行解析

  5.編寫map函數,reduce函數

  1. 將其許可權作出相應修改
    chmod a+x /home/hadoop/mapper.pychmod a+x /home/hadoop/wc/reducer.py
  2. 本機上測試回合代碼

放到HDFS上運行

將之前爬取的文字檔上傳到hdfs上

用Hadoop Streaming命令提交任務

查看運行結果

 

用Python編寫WordCount程式任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.