Hadoop綜合大做業加上之前漏掉的做業

  1.啓動hadoopphp

 

       2.Hdfs上建立文件夾並查看html

上傳英文詞頻統計文本至hdfsmysql

 

 

啓動Hivesql

導入文件內容到表docs並查看api

進行詞頻統計,結果放在表t_word_count2裏數據結構

查看統計結果app

 

hive基本操做與應用

經過hadoop上的hive完成WordCountssh

啓動hadoop函數

ssh localhost
cd /usr/local/hadoop
./sbin/start-dfs.sh
cd /usr/local/hive/lib
service mysql start
start-all.shoop

Hdfs上建立文件夾

hdfs dfs -mkdir test1
hdfs dfs -ls /user/hadoop

 

上傳文件至hdfs

hdfs dfs -put ./try.txt test1
hdfs dfs -ls /user/hadoop/test1

 

啓動Hive

hive

 

建立原始文檔表

create table docs(line string)

 

用HQL進行詞頻統計,結果放在表word_count裏

create table word_count as select word,count(1) as count from (select explode(split(line," ")) as word from docs) word group by word order by word;

導入文件內容到表docs並查看

load data inpath '/user/hadoop/tese1/try.txt' overwrite into table docs

select  from  docs
 

爬蟲大做業

f = open("C:/Users/ZD/PycharmProjects/test/test.txt", 'w+', encoding='utf8')
import jieba
import requests
from bs4 import BeautifulSoup


def songlist(url):
res = requests.get(url)
res.encoding = 'UTF-8'
soup = BeautifulSoup(res.text, 'html.parser')
songname = soup.select('.song')
for i in songname[1:]:
url = i.select('a')[0].attrs['href']
songread(url)


def songread(url):
f = open("C:/Users/ZD/PycharmProjects/test/test.txt", 'w+', encoding='utf8')
res = requests.get(url)
res.encoding = 'UTF-8'
soup = BeautifulSoup(res.text, 'html.parser')
song = soup.select('.lrcItem')
for i in song:
f.write(i.text)


songlist('http://www.kuwo.cn/geci/a_336/?')
f = open("C:/Users/ZD/PycharmProjects/test/test.txt", 'r', encoding='utf8')
str = f.read()
f.close()

wordList = jieba.cut(str)
wordList = list(jieba.cut(str))

wordDic = {}
for i in set(wordList):
wordDic[i] = wordList.count(i)

sort_word = sorted(wordDic.items(), key=lambda d: d[1], reverse=True)
for i in range(60):
print(sort_word[i])

fo = open("C:/Users/ZD/PycharmProjects/test/test1.txt", 'w', encoding='utf8')
for i in range(60):
fo.write(sort_word[i][0] + '\n')

fo.close()

熟悉經常使用的HDFS操做

  1. 在本地Linux文件系統的「/home/hadoop/」目錄下建立一個文件txt,裏面能夠隨意輸入一些單詞.
    cd /usr/local/hadoop
    touch text.txt
  2. 在本地查看文件位置(ls)
    ls -al
  3. 在本地顯示文件內容
    cat text.txt
  4. 使用命令把本地文件系統中的「txt」上傳到HDFS中的當前用戶目錄的input目錄下。
    ./sbin/start-dfs.sh
    ./bin/hdfs dfs -mkdir -p /user/hadoop ./bin/hdfs dfs -mkdir input ./bin/hdfs dfs -put ./test.txt input
  5. 查看hdfs中的文件(-ls)
    ./sbin/start-dfs.sh
  6. 顯示hdfs中該的文件內容
    ./bin/hdfs dfs -ls input
    ./bin/hdfs dfs -cat input/test.txt
  7. 刪除本地的txt文件並查看目錄
    cd
    rm test.txt
  8. 從hdfs中將txt下載地本地原來的位置。
    ./bin/hdfs dfs -get input/test.txt ~/test.txt
  9. 從hdfs中刪除txt並查看目錄

    ./bin/hdfs dfs -rm news.txt

    ./bin/hdfs  dfs -ls input

     

    • 向HDFS中上傳任意文本文件,若是指定的文件在HDFS中已經存在,由用戶指定是追加到原有文件末尾仍是覆蓋原有的文件;
      if $(hdfs dfs -test -e text.txt);
      then $(hdfs dfs -appendToFile local.txt text.txt);
      else $(hdfs dfs -copyFromLocal -f local.txt text.txt);
      fi
    • 從HDFS中下載指定文件,若是本地文件與要下載的文件名稱相同,則自動對下載的文件重命名;
      if $(hdfs dfs -test -e file:///usr/hadoop/text.txt);
      then $(hdfs dfs -copyToLocal text.txt ./text2.txt); 
      else $(hdfs dfs -copyToLocal text.txt ./text.txt); 
      fi
    • 將HDFS中指定文件的內容輸出到終端中;
      hdfs dfs -cat text.txt
    • 顯示HDFS中指定的文件的讀寫權限、大小、建立時間、路徑等信息;
      hdfs dfs -ls -h text.txt
    • 給定HDFS中某一個目錄,輸出該目錄下的全部文件的讀寫權限、大小、建立時間、路徑等信息,若是該文件是目錄,則遞歸輸出該目錄下全部文件相關信息;
      hdfs dfs -ls -R -h /user/hadoop
    • 提供一個HDFS內的文件的路徑,對該文件進行建立和刪除操做。若是文件所在目錄不存在,則自動建立目錄;
      if $(hdfs dfs -test -d dir1/dir2);
      then $(hdfs dfs -touchz dir1/dir2/filename); 
      else $(hdfs dfs -mkdir -p dir1/dir2 && hdfs dfs -touchz dir1/dir2/filename); 
      fi
      hdfs dfs -rm dir1/dir2/filename
    • 提供一個HDFS的目錄的路徑,對該目錄進行建立和刪除操做。建立目錄時,若是目錄文件所在目錄不存在則自動建立相應目錄;刪除目錄時,由用戶指定當該目錄不爲空時是否還刪除該目錄;
      建立目錄:hdfs dfs -mkdir -p dir1/dir2
      刪除目錄:hdfs dfs -rmdir dir1/dir2
      強制刪除目錄:hdfs dfs -rm -R dir1/dir2
    • 向HDFS中指定的文件追加內容,由用戶指定內容追加到原有文件的開頭或結尾;
      追加到文件末尾:hdfs dfs -appendToFile local.txt text.txt
      追加到文件開頭:
      hdfs dfs -get text.txt
      cat text.txt >> local.txt
      hdfs dfs -copyFromLocal -f text.txt text.txt
    • 刪除HDFS中指定的文件;
      hdfs dfs -rm text.txt
    • 刪除HDFS中指定的目錄,由用戶指定目錄中若是存在文件時是否刪除目錄;
      刪除目錄:hdfs dfs -rmdir dir1/dir2
      強制刪除目錄:hdfs dfs -rm -R dir1/dir2
    • 在HDFS中,將文件從源路徑移動到目的路徑。
    • hdfs dfs -mv text.txt text2.txt

數據結構化與保存

1. 將新聞的正文內容保存到文本文件。

2. 將新聞數據結構化爲字典的列表:

  • 單條新聞的詳情-->字典news
  • 一個列表頁全部單條新聞彙總-->列表newsls.append(news)
  • 全部列表頁的全部新聞彙總列表newstotal.extend(newsls)

3. 安裝pandas,用pandas.DataFrame(newstotal),建立一個DataFrame對象df.

4. 經過df將提取的數據保存到csv或excel 文件。

5. 用pandas提供的函數和方法進行數據分析:

  • 提取包含點擊次數、標題、來源的前6行數據
  • 提取‘學校綜合辦’發佈的,‘點擊次數’超過3000的新聞。
  • 提取'國際學院'和'學生工做處'發佈的新聞。

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas

#獲取點擊次數
def getClickCount(newsUrl):
newId=re.search('\_(.*).html',newsUrl).group(1).split('/')[1]
clickUrl="http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newId)
clickStr = requests.get(clickUrl).text
count = re.search("hits'\).html\('(.*)'\);", clickStr).group(1)
return count

#獲取新聞詳情
def getNewsDetail(newsurl):
resd=requests.get(newsurl)
resd.encoding='utf-8'
soupd=BeautifulSoup(resd.text,'html.parser')

news={}
news['title']=soupd.select('.show-title')[0].text
# news['newsurl']=newsurl
info=soupd.select('.show-info')[0].text
news['dt']=datetime.strptime(info.lstrip('發佈時間:')[0:19],'%Y-%m-%d %H:%M:%S')
news['click'] = int(getClickCount(newsurl))
if info.find('來源')>0:
news['source'] =info[info.find('來源:'):].split()[0].lstrip('來源:')
else:
news['source']='none'
if info.find('做者:') > 0:
news['author'] = info[info.find('做者:'):].split()[0].lstrip('做者:')
else:
news['author'] = 'none'
# news['content']=soupd.select('.show-content')[0].text.strip()

#獲取文章內容並寫入到文件中
content=soupd.select('.show-content')[0].text.strip()
writeNewsContent(content)

return news

def getListPage(listPageUrl):
res=requests.get(listPageUrl)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')

newsList=[]
for news in soup.select('li'):
if len(news.select('.news-list-title'))>0:
a=news.select('a')[0].attrs['href']
newsList.append(getNewsDetail(a))
return (newsList)

#數據寫入文件
def writeNewsContent(content):
f=open('gzccNews.txt','a',encoding='utf-8')
f.write(content)
f.close()

def getPageNumber():
ListPageUrl="http://news.gzcc.cn/html/xiaoyuanxinwen/"
res=requests.get(ListPageUrl)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
n = int(soup.select('.a1')[0].text.rstrip('條'))//10+1
return n


newsTotal=[]
firstPage='http://news.gzcc.cn/html/xiaoyuanxinwen/'
newsTotal.extend(getListPage(firstPage))

n=getPageNumber()
for i in range(n,n+1):
listUrl= 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
newsTotal.extend(getListPage(listUrl))

df=pandas.DataFrame(newsTotal)
# df.to_excel("news.xlsx")

# print(df.head(6))
# print(df[['author','click','source']])
# print(df[df['click']>3000])

sou=['國際學院','學生工做處']print(df[df['source'].isin(sou)])

相關文章
相關標籤/搜索