01.Crawling

url_request

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Feb 17 11:08:44 2019
  4.  
  5. @author: 502-03
  6. 1.anaconda Prompt실행
  7. 2.python -m pip install --upgrade pip
  8. 3.pip install beautifulsoup4
  9. """
  10.  
  11. import urllib.request #url 요청
  12. from bs4 import BeautifulSoup #html 파씽
  13.  
  14. url="http://www.naver.com/index.html"
  15.  
  16. #1.원격서버 파일 요청
  17. rst=urllib.request.urlopen(url)
  18. print(rst) #<http.client.HTTPResponse object at 0x000000000E21F940>
  19.  
  20. data_src=rst.read() #source read
  21. print(data_src)
  22. """
  23. b'<!doctype html>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<html lang="ko">\n<head>
  24. ....
  25. """
  26.  
  27. #2.html 파싱:src->html문서
  28. html=data_src.decode('utf-8') #디코딩
  29. soup=BeautifulSoup(html,'html.parser')
  30. print(soup)
  31. """
  32. </script>
  33. <title>NAVER</title>
  34. </meta></meta></meta></meta></meta></head>
  35. <style>
  36. """
  37.  
  38. #3.tag기반 수집
  39. link=soup.find('a') #하나만 가져옴
  40. print(link)
  41. """
  42. <a href="#news_cast" onclick="document.getElementById('news_cast2').tabIndex = -1;
  43. document.getElementById('news_cast2').focus();return false;">
  44. <span>연합뉴스 바로가기</span></a>
  45. """
  46. print('a tag 내용',link.string)#a tag 내용 연합뉴스 바로가기
  47.  
  48. links=soup.find_all('a')#전부 가져오기
  49. print('a tag size',len(links))#a tag size 335
  50. links_data=[] #빈 리스트
  51.  
  52. print(a.string)
  53. links_data.append(a.string)
  54.  
  55. print("links_data",len(links_data))#links_data 341
  56. print(links_data)
  57. """
  58. ['연합뉴스 바로가기', '주제별캐스트 바로가기', '타임스퀘어 바로가기', '쇼핑캐스트 바로가기', '로그인 바로가기',
  59. ....
  60. '네이버 정책', '고객센터', 'NAVER Corp.']
  61. """

selector

  1. # -*- coding: utf-8 -*-
  2. """
  3. - 선택자(selector) 이용 문서 수집
  4. -> 웹 문서 디자인(css)
  5. -> id(#), class(.)
  6. -> select_one('선택자') : 하나 요소 추출
  7. -> select('선택자') : 여러 개 요소 추출
  8. """
  9.  
  10. from bs4 import BeautifulSoup #html 파싱
  11.  
  12. #1.html파일 가져오기
  13. file=open("../data/selector.html",mode='r',encoding='utf-8')
  14. data_src=file.read()
  15. print(data_src)
  16. """
  17. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  18. <html>
  19. <head>
  20. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  21. <title>id/class 선택자, 꾸미기</title>
  22. <style type="text/css">
  23. """
  24.  
  25. #2.html파싱
  26. html=BeautifulSoup(data_src,'html.parser')
  27. print(html)
  28. """
  29.  
  30. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  31.  
  32. <html>
  33. <head>
  34. <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  35. <title>id/class 선택자, 꾸미기</title>
  36. <style type="text/css">
  37. """
  38.  
  39. #3.selector 기반 수집
  40.  
  41. #1) id선택자: selector("tab#id명"))
  42. table=html.select_one('table#tab')
  43. print(table)
  44. """
  45. <table border="1" id="tab">
  46. <tr> <!-- 1행 -->
  47. <!-- 제목 열 : th -->
  48. <th id="id"> 학번 </th>
  49. ...
  50. <td> you@naver.com </td>
  51. </tr>
  52. </table>
  53. """
  54.  
  55. #2)id 선택자 >하위 태그
  56. th=html.select_one('table#tab > tr > th')
  57. print(th) #<th id="id"> 학번 </th>
  58.  
  59. ths=html.select('table#tab > tr > th')
  60. print(ths)
  61. """
  62. [<th id="id"> 학번 </th>, <th id="name"> 이름 </th>, <th id="major"> 학과 </th>, <th id="email"> 이메일 </th>]
  63. """
  64.  
  65. for th in ths:#<th id="id"> 학번 </th>
  66. print(th.string)
  67. """
  68. 학번
  69. 이름
  70. 학과
  71. 이메일
  72. """
  73.  
  74. #2) class 선택 :select('tag.class명')
  75. # -5행->홀수 행
  76.  
  77. # (1) 계층적 접근
  78. trs=html.select('table#tab > tr.odd')
  79. print(trs)
  80. """
  81. [<tr class="odd"> <!-- 3행(홀수) -->
  82. <td> 201602 </td>
  83. <td> 이순신 </td>
  84. <td> 해양학과 </td>
  85. <td> lee@naver.com </td>
  86. </tr>, <tr class="odd"> <!-- 5행 -->
  87. <td> 201604 </td>
  88. <td> 유관순 </td>
  89. <td> 유아교육 </td>
  90. <td> you@naver.com </td>
  91. </tr>]
  92. """
  93. tds_data=[]
  94. for tr in trs:# 2
  95. tds=tr.find_all('td')
  96. for td in tds:
  97. print(td.string)
  98. tds_data.append(td.string)
  99. """
  100. 201602
  101. 이순신
  102. 해양학과
  103. lee@naver.com
  104. 201604
  105. 유관순
  106. 유아교육
  107. you@naver.com
  108. """
  109.  
  110. #(2) 직접 접근 :tag[속성=값]
  111. trs=html.select('tr[class=odd]')
  112. print(trs)
  113. """
  114. [<tr class="odd"> <!-- 3행(홀수) -->
  115. <td> 201602 </td>
  116. <td> 이순신 </td>
  117. <td> 해양학과 </td>
  118. <td> lee@naver.com </td>
  119. </tr>, <tr class="odd"> <!-- 5행 -->
  120. <td> 201604 </td>
  121. <td> 유관순 </td>
  122. <td> 유아교육 </td>
  123. <td> you@naver.com </td>
  124. </tr>]
  125. """

newsCrawling

  1. # -*- coding: utf-8 -*-
  2. """
  3. news Crawling
  4. url='http://media.daum.net'
  5. """
  6.  
  7. import requests #url 요청
  8. from bs4 import BeautifulSoup #html 파싱
  9.  
  10. url='http://media.daum.net'
  11.  
  12. #1.url 요청
  13. src=requests.get(url)
  14. print(src) #<Response [200]>
  15.  
  16. data_src=src.text # source text
  17.  
  18. #2.html 파싱
  19. html=BeautifulSoup(data_src,'html.parser')
  20. print(html)
  21.  
  22. #3.select(tag[속성=값])
  23. # <strong class="tit_g"><a href="http://v.media.daum.net/v/20190217083008573" class="link_txt">美, 방위비 또 두 자릿수 인상 요구 가능성..韓 대응 방안은</a><span class="txt_view">뉴시스</span></strong>
  24. links=html.select("a[class=link_txt]")
  25.  
  26. creawling_data=[]#내용저장
  27. cnt =0;
  28. for link in links:
  29. cnt+=1
  30. cont=str(link.string) #문자 변환
  31. #print(cont)
  32. print(cnt,'-',cont.strip()) # 줄바꿈 ,공백 ,불용어 제거
  33. creawling_data.append(cont.split())
  34.  
  35. """
  36. 1 - 트럼프 "무역협상 생산적..中 수십억달러 관세로 "
  37. 2 - "미중 무역전쟁..지적재산권 마찰도 변수"
  38. 3 - 트럼프도 시진핑도 긍정적 자평..기로에 선 무역전쟁
  39. 4 - 미·중 무역전쟁 '휴전' 연장 가능성..우리나라 영향은...
  40. 5 - 中언론도 무역협상 낙관론.."미중 모두를 위한 합의해야...
  41. """
  42.  
  43. #변수 ->text file save
  44. file=open('../data/crawling_data.txt',
  45. mode='w',encoding='utf-8')
  46.  
  47. #list -> str 변환
  48. file.write(str(creawling_data))
  49. file.close()
  50. print("file save commit")

02.NLP

jpype_test

  1. # -*- coding: utf-8 -*-
  2. """
  3. java 가상머신 사용여부
  4. """
  5. import jpype
  6.  
  7. path=jpype.getDefaultJVMPath()
  8. print(path)#C:\Program Files\Java\jdk1.8.0_181\jre\bin\server\jvm.dll

konlpy

  1. # -*- coding: utf-8 -*-
  2. """
  3. konlpy인스톨 여부
  4. pip install konlpy
  5. """
  6.  
  7. from konlpy.tag import Kkma
  8.  
  9. #Kkma object
  10. kkma=Kkma()
  11.  
  12. #문단 -> 문장 추출
  13. para="형태소 분석을 사장입니다.나는 홍길동 이고 age는 28세 입니다."
  14.  
  15. ex_sent=kkma.sentences(para)
  16. print(ex_sent)
  17. """
  18. ['형태소 분석을 사장입니다.', '나는 홍길동 이고 age는 28세 입니다.']
  19. """
  20.  
  21. #문단 -> 명사 추출
  22. ex_nouns=kkma.nouns(para)
  23. print(ex_nouns)
  24. """
  25. ['형태소', '분석', '사장', '나', '홍길동', '28', '28세', '세']
  26. """
  27.  
  28. #문단 -> 형태소 추출
  29. ex_pos=kkma.pos(para)
  30. print(ex_pos) #[(text,text class)]
  31. """
  32. [('형태소', 'NNG'), ('분석', 'NNG'), ('을', 'JKO'), ('사장', 'NNG'), ('이', 'VCP'),
  33. ('ㅂ니다', 'EFN'), ('.', 'SF'), ('나', 'NP'), ('는', 'JX'), ('홍길동', 'NNG'),
  34. ('이', 'VCP'), ('고', 'ECE'), ('age', 'OL'), ('는', 'JX'), ('28', 'NR'),
  35. ('세', 'NNM'), ('이', 'VCP'), ('ㅂ니다', 'EFN'), ('.', 'SF')]
  36. """
  37. '''
  38. 형태소 : 언어에 있어서 분해 가능한 최소한의 의미를 가진 단위
  39. NNG 일반 명사 NNP 고유 명사 NNB 의존 명사 NR 수사 NP 대명사 VV 동사
  40. VA 형용사 VX 보조 용언 VCP 긍정 지정사 VCN 부정 지정사 MM 관형사
  41. MAG 일반 부사 MAJ 접속 부사 IC 감탄사 JKS 주격 조사 JKC 보격 조사
  42. JKG 관형격 조사 JKO 목적격 조사 JKB 부사격 조사 JKV 호격 조사
  43. JKQ 인용격 조사 JC 접속 조사 JX 보조사 EP 선어말어미 EF 종결 어미
  44. EC 연결 어미 ETN 명사형 전성 어미 ETM 관형형 전성 어미 XPN 체언 접두사
  45. XSN 명사파생 접미사 XSV 동사 파생 접미사 XSA 형용사 파생 접미사 XR 어근
  46. SF 마침표, 물음표, 느낌표 SE 줄임표 SS 따옴표,괄호표,줄표
  47. SP 쉼표,가운뎃점,콜론,빗금 SO 붙임표(물결,숨김,빠짐)
  48. SW 기타기호 (논리수학기호,화폐기호) SH 한자 SL 외국어 SN 숫자
  49. NF 명사추정범주 NV 용언추정범주 NA 분석불능범
  50. '''
  51.  
  52. #NNG:일반 명사 NNP:고유 명사 NP:대명사
  53. ex_pos2=[] #명사 추출
  54. for (text,text_class) in ex_pos:#(text,text class)
  55. if text_class=='NNG' or text_class=='NNP' or text_class=='NP':
  56. ex_pos2.append(text)
  57.  
  58. print(ex_pos2)#['형태소', '분석', '사장', '나', '홍길동']

03.WordCloud

ex_nouns

  1. # -*- coding: utf-8 -*-
  2. """
  3. 1.test file 읽기
  4. 2.명사 추출 : Kkma
  5. 3.전처리 :단어 길이 제한 ,숫자 제이
  6. 4.word cloud시각화
  7. """
  8. from konlpy.tag import Kkma
  9.  
  10. #object
  11. kkma=Kkma()
  12.  
  13. #1.text file읽기
  14. file=open("../data/text_data.txt",mode='r',encoding="utf-8")
  15. docs=file.read() #text전체 읽기
  16. file.close()
  17. print(docs)
  18. """
  19. 형태소 분석을 시작합니다. 나는 데이터 분석을 좋아합니다.
  20. 직업은 데이터 분석 전문가 입니다. Text mining 기법은 2000대 초반에 개발된 기술이다.
  21. """
  22.  
  23. #1).doc -> sentence
  24. ex_sent=kkma.sentences(docs)
  25.  
  26. print(ex_sent)
  27. """
  28. ['형태소 분석을 시작합니다.',
  29. '나는 데이터 분석을 좋아합니다.',
  30. '직업은 데이터 분석 전문가 입니다.',
  31. 'Text mining 기법은 2000대 초반에 개발된 기술이다.']
  32. """
  33.  
  34. for sent in ex_sent:
  35. print(sent)
  36. """
  37. 형태소 분석을 시작합니다.
  38. 나는 데이터 분석을 좋아합니다.
  39. 직업은 데이터 분석 전문가 입니다.
  40. Text mining 기법은 2000대 초반에 개발된 기술이다.
  41. """
  42.  
  43. #2).docs -> nount 추출
  44. ex_nouns=kkma.nouns(docs) #중복 명사 추출 않됨
  45.  
  46. print(ex_nouns)
  47. """
  48. ['형태소', '분석', '나', '데이터', '직업', '전문가',
  49. '기법', '2000', '2000대', '대', '초반', '개발', '기술']
  50. """
  51.  
  52. from re import match
  53.  
  54. #2~3.중복 단어 추출 -> 전처리 과정(숫자,길이 1개 제외)
  55. nouns_words =[]#list
  56. nouns_count={} #set or dict
  57. for sent in ex_sent:#문장들
  58. for nouns in kkma.nouns(sent):#단어들
  59. #전처리 (숫자,길이 1개 제외)
  60. if len(str(nouns))>1 and not(match('^[0-9]',nouns)):
  61. nouns_words.append(nouns)
  62. #key=word :value:count
  63. nouns_count[nouns]=nouns_count.get(nouns,0)+1
  64.  
  65. print(len(nouns_words))#15->12
  66. """
  67. ['형태소', '분석', '데이터', '분석', '직업', '데이터',
  68. '분석', '전문가', '기법', '초반', '개발', '기술']
  69. """
  70.  
  71. print(nouns_count)
  72. """
  73. {'형태소': 1, '분석': 3, '데이터': 2, '직업': 1,
  74. '전문가': 1, '기법': 1, '초반': 1, '개발': 1, '기술': 1}
  75. """
  76.  
  77. #4.word cloud시각화
  78. from collections import Counter
  79.  
  80. #1)dict->Counter 객체
  81. word_count=Counter(nouns_count)
  82.  
  83. #2)top word
  84. top5=word_count.most_common(5)
  85. print(top5)
  86. """
  87. [('분석', 3), ('데이터', 2), ('형태소', 1), ('직업', 1), ('전문가', 1)]
  88. """
  89. #3)word cloud 시각화 :package 시각
  90.  
  91. import pytagcloud
  92. '''
  93. Anaconda Prompt에서
  94. pip install pygame
  95. pip install pytagcloud
  96. pip install simplejson
  97. '''
  98.  
  99. # tag에 color, size, tag 사전 구성
  100. word_count_list = pytagcloud.make_tags(top5, maxsize=80)
  101. # maxsize : 최대 글자크기
  102. print(word_count_list)
  103. '''
  104. [{'color': (91, 34, 34), 'size': 109, 'tag': '분석'}, {'color': (95, 159, 59), 'size': 80, 'tag': '데이터'}, {'color': (194, 214, 193), 'size': 47, 'tag': '형태소'}]
  105. '''
  106.  
  107. pytagcloud.create_tag_image(word_count_list,
  108. 'wordcloud.jpg',
  109. size=(900, 600),
  110. fontname='korean', rectangular=False)
  111. '''
  112. 한글 단어 구름 시각화 Error 수정
  113. C:\Anaconda3\Lib\site-packages\pytagcloud\fonts 폴더에서
  114. 1. fonts.json 파일 내용 수정
  115. [
  116. {
  117. "name": "korean",
  118. "ttf": "malgun.ttf",
  119. 2. C:\Windows\Fonts 폴더에서 '맑은 고딕' 서체 복사/fonts 폴더 붙여넣기
  120. 3. create_tag_image(fontname='korean') 속성 추가
  121. '''

news_wordCloud

  1. # -*- coding: utf-8 -*-
  2. """
  3. news crawling data file
  4. - word cloud 시각화
  5. """
  6.  
  7. from konlpy.tag import Kkma
  8.  
  9. #object 생성
  10. kkma =Kkma()
  11.  
  12. #1.text file load
  13. file=open("../data/crawling_data.txt",
  14. encoding='utf-8')
  15. crawling_data=file.read()
  16. file.close()
  17. print(crawling_data)
  18. """
  19. [['트럼프', '"무역협상', '생산적..中', '수십억달러', '관세로', '"'],
  20. ['"미중', '무역전쟁..지적재산권', '마찰도', '', '변수"'],
  21. ['트럼프도', '시진핑도', '긍정적', '자평..기로에', '선', '무역전쟁'],
  22. ...
  23. ['베니스', '비엔날레', '작가', '선정에', '송성각', '관여', '의혹', '관련', '정정보도문']]
  24. """
  25.  
  26. #2.docs-> sentences 추출
  27. ex_sent=kkma.sentences(crawling_data)
  28.  
  29. print(ex_sent)
  30.  
  31. #3문장->명사 추출
  32. # 4. text 전처리 : 숫자, 1개 단어 제외
  33. # 5. word count : dict
  34. ex_nouns=[] #list
  35. word_count={} #dict
  36. for sent in ex_sent:# 문장들
  37. for nouns in kkma.nouns(sent):# 단어들
  38. if len(str(nouns))>1 and not(match('^[0-9]',nouns)):
  39. ex_nouns.append(nouns)
  40. word_count[nouns]=word_count.get(nouns,0)+1
  41.  
  42. print(ex_nouns)
  43. print(word_count)
  44.  
  45. # 5. Counter 객체 : top10 추출
  46. from collections import Counter
  47. word_count=Counter(word_count)
  48. top10=word_count.most_common(10)
  49. print(top10)
  50. """
  51. [('미', 4), ('트럼프', 3), ('억', 3), ('중', 3), ('선', 3), ('조', 3), ('정', 3), ('정정보', 3), ('정보', 3), ('문', 3)]
  52. """
  53.  
  54. # 6. word cloud 시각화
  55. import pytagcloud
  56. '''
  57. Anaconda Prompt에서
  58. pip install pygame
  59. pip install pytagcloud
  60. pip install simplejson
  61. '''
  62. # tag에 color, size, tag 사전 구성
  63. word_count_list = pytagcloud.make_tags(top10, maxsize=80)
  64. # maxsize : 최대 글자크기
  65. print(word_count_list)
  66. '''
  67. [{'color': (91, 34, 34), 'size': 109, 'tag': '분석'}, {'color': (95, 159, 59), 'size': 80, 'tag': '데이터'}, {'color': (194, 214, 193), 'size': 47, 'tag': '형태소'}]
  68. '''
  69.  
  70. pytagcloud.create_tag_image(word_count_list,
  71. 'news_wordcloud.jpg',
  72. size=(900, 600),
  73. fontname='korean', rectangular=False)
  74. '''
  75. 한글 단어 구름 시각화 Error 수정
  76. C:\Anaconda3\Lib\site-packages\pytagcloud\fonts 폴더에서
  77. 1. fonts.json 파일 내용 수정
  78. [
  79. {
  80. "name": "korean",
  81. "ttf": "malgun.ttf",
  82. 2. C:\Windows\Fonts 폴더에서 '맑은 고딕' 서체 복사/fonts 폴더 붙여넣기
  83. 3. create_tag_image(fontname='korean') 속성 추가
  84. '''

04.SparseMatrix

TfidfVectorizer

  1. # -*- coding: utf-8 -*-
  2. """
  3. TfidfVectorizer 기능 : Tfidf(가중치 적용 방법) 단어 벡터 생성기
  4. 1. 단어 생성기 : 문장 -> 단어(word)
  5. 2. 단어 사전(word dict) : {word : 고유수치}
  6. 3. 희소 행렬(sparse matrix) : 단어 출현비율에 따른 가중치(TF, TFiDF)
  7. 1) TF : 단어 출현빈도수 -> 가중치 적용(빈도수 높은 가중 높다.)
  8. 2) TFiDF : 단어 출현빈도수 x 문서 출현빈도수에 역수(단어 중요도)
  9. -> TFiDF = tf(d, t) x log(n/df(t))
  10. """
  11.  
  12. from sklearn.feature_extraction.text import TfidfVectorizer
  13.  
  14. #문장
  15. sentences = [
  16. "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
  17. "Professor Plum has a green plant in his study.",
  18. "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
  19. ]
  20.  
  21. #1.단어 생성기:문장->단어(word)
  22. tfidf_fit=TfidfVectorizer().fit(sentences)
  23. print(tfidf_fit)#object info
  24. """
  25. TfidfVectorizer(analyzer='word', binary=False, decode_error='strict',
  26. dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
  27. lowercase=True, max_df=1.0, max_features=None, min_df=1,
  28. ngram_range=(1, 1), norm='l2', preprocessor=None, smooth_idf=True,
  29. stop_words=None, strip_accents=None, sublinear_tf=False,
  30. token_pattern='(?u)\\b\\w\\w+\\b', tokenizer=None, use_idf=True,
  31. vocabulary=None)
  32. """
  33.  
  34. #2.단어 사전(word dict) : {word:고유수치}
  35. voca=tfidf_fit.vocabulary_
  36. print('word size=',len(voca))#word size= 31
  37. print(voca)# 'mr': 14, #14는 고유숫자
  38. """
  39. {'mr': 14, 'green': 5, 'killed': 11, 'colonel': 2, 'mustard': 15, 'in': 9,
  40. 'the': 24, 'study': 23, 'with': 30, 'candlestick': 1, 'is': 10, 'not': 17,
  41. 'very': 25, 'nice': 16, 'fellow': 3, 'professor': 21, 'plum': 20, 'has': 6,
  42. 'plant': 19, 'his': 8, 'miss': 13, 'scarlett': 22, 'watered': 27, 'while': 29,
  43. 'he': 7, 'was': 26, 'away': 0, 'from': 4, 'office': 18, 'last': 12, 'week': 28}
  44. """
  45.  
  46. #영문자 오름차순:word embedding
  47.  
  48. #3.희소 행렬(sparse matrix) :text:분석 DTM(행:D ,열:T)
  49. tfidf=TfidfVectorizer()#object
  50. sparse_tfidf=tfidf.fit_transform(sentences)
  51. print(type(sparse_tfidf))#<class 'scipy.sparse.csr.csr_matrix'>
  52. print(sparse_tfidf.shape)#DTM=(3행(Doc), 31열(Term))
  53. print("1.scipy.sparse.matrix")
  54. print(sparse_tfidf)
  55. """
  56. (row:doc,col:term) 가중치 (weight)=Tfidf
  57. (0, 14) 0.4411657657527482:'mr'
  58. (0, 5) 0.26055960805891015:'green'
  59. (1, 5) 0.2690399207469689 :'green'
  60. (1, 8) 0.34643788271971976
  61. (2, 5) 0.15978698032384395
  62. (2, 21) 0.2057548299742193
  63. (2, 20) 0.2057548299742193
  64. ...
  65. """
  66.  
  67. print("2.numpy sparse.matrix")
  68. #scipy->numpy 형변환
  69. tfidf_arr=sparse_tfidf.toarray()
  70. print(tfidf_arr.shape) #(3, 31)
  71. print(type(tfidf_arr))#<class 'numpy.ndarray'>
  72. print(tfidf_arr)
  73. """
  74. [[0. 0.22058288 0.22058288 0.22058288 0. 0.26055961
  75. 0. 0. 0. 0.16775897 0.22058288 0.22058288
  76. 0. 0. 0.44116577 0.22058288 0.22058288 0.22058288
  77. 0. 0. 0. 0. 0. 0.16775897
  78. 0.44116577 0.22058288 0. 0. 0. 0.
  79. 0.22058288]
  80. [0. 0. 0. 0. 0. 0.26903992
  81. 0.45552418 0. 0.34643788 0.34643788 0. 0.
  82. 0. 0. 0. 0. 0. 0.
  83. 0. 0.34643788 0.34643788 0.34643788 0. 0.34643788
  84. 0. 0. 0. 0. 0. 0.
  85. 0. ]
  86. [0.27054288 0. 0. 0. 0.27054288 0.15978698
  87. 0. 0.27054288 0.20575483 0. 0. 0.
  88. 0.27054288 0.27054288 0. 0. 0. 0.
  89. 0.27054288 0.20575483 0.20575483 0.20575483 0.27054288 0.
  90. 0. 0. 0.27054288 0.27054288 0.27054288 0.27054288
  91. 0. ]]
  92. """
  93.  
  94. """
  95. 1.scipy sparse matrix
  96. -> tensorflow model
  97. 2.numpy sparse matrix
  98. -> sklean model
  99. """

python TextMining的更多相关文章

  1. [Python] 机器学习库资料汇总

    声明:以下内容转载自平行宇宙. Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: ...

  2. python数据挖掘领域工具包

    原文:http://qxde01.blog.163.com/blog/static/67335744201368101922991/ Python在科学计算领域,有两个重要的扩展模块:Numpy和Sc ...

  3. [resource]Python机器学习库

    reference: http://qxde01.blog.163.com/blog/static/67335744201368101922991/ Python在科学计算领域,有两个重要的扩展模块: ...

  4. [转]Python机器学习工具箱

    原文在这里  Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: 比较成熟的(广播 ...

  5. python版本及ML库

    一:关于Python版本的选择问题 关于Python的选择问题:要看学术界能不能把科学库迁移到Python3. 1:多个版本共用: 最近发现SciPy的最高版本是3.2,只能是退而求其次,不使用最新版 ...

  6. Python中的多进程与多线程(一)

    一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...

  7. Python高手之路【六】python基础之字符串格式化

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  8. Python 小而美的函数

    python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况   any any(iterable) ...

  9. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

随机推荐

  1. 10.3 Vue 路由系统

     Vue 路由系统  简单示例 main.js  import Vue from 'vue' import App from './App.vue' //https://router.vuejs.or ...

  2. Magento 2 Block模板终极指南

    /view/frontend/page_layout/2columns-left.xml <layout xmlns:xsi="http://www.w3.org/2001/XMLSc ...

  3. java 11 完全支持Linux容器(包括Docker)

    许多运行在Java虚拟机中的应用程序(包括Apache Spark和Kafka等数据服务以及传统的企业应用程序)都可以在Docker容器中运行.但是在Docker容器中运行Java应用程序一直存在一个 ...

  4. [SHOI2008]仙人掌图 II——树形dp与环形处理

    题意: 给定一个仙人掌,边权为1 距离定义为两个点之间的最短路径 直径定义为距离最远的两个点的距离 求仙人掌直径 题解: 类比树形dp求直径. f[i]表示i向下最多多长 处理链的话,直接dp即可. ...

  5. jieba 库的使用和好玩的词云

    jieba库的使用: (1)  jieba库是一款优秀的 Python 第三方中文分词库,jieba 支持三种分词模式:精确模式.全模式和搜索引擎模式,下面是三种模式的特点. 精确模式:试图将语句最精 ...

  6. JavaJDBC整理

    1.1.1    导入驱动jar包 创建lib目录,用于存放当前项目需要的所有jar包 选择jar包,右键执行build path / Add to Build Path 前版本 package co ...

  7. SpringBoot(七):SpringBoot整合Swagger2

    原文地址:https://blog.csdn.net/saytime/article/details/74937664 手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文 ...

  8. [物理学与PDEs]第4章第2节 反应流体力学方程组 2.2 反应流体力学方程组形式的化约

    1.  粘性热传导反应流体力学方程组 $$\beex \bea \cfrac{\rd \rho}{\rd t}&+\rho \Div{\bf u}=0,\\ \cfrac{\rd Z}{\rd ...

  9. [物理学与PDEs]第2章第2节 粘性流体力学方程组 2.5 粘性热传导流体动力学方程组的数学结构

    1.  粘性热传导流体动力学方程组可化为 $$\beex \bea \cfrac{\p \rho}{\p t}&+({\bf u}\cdot\n)\rho=-\rho \Div{\bf u}, ...

  10. webpack安装异常

    webpack中文指南:https://zhaoda.net/webpack-handbook/index.html 今天中午,我用   cnpm install   重新下载了一下项目的依赖,爆了一 ...