wordcloudで凛として時雨の歌詞を可視化してみた
凛として時雨の歌詞でよく使われる単語を可視化してみた。
歌詞データをスクレイピング -> janomeで分かち書き -> wordcloudで可視化という流れになっている。
コード
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import urllib.request as req from janome.tokenizer import Tokenizer #jupyterでmatplotlibを使うときに記述 %matplotlib inline import matplotlib.pyplot as plt from wordcloud import WordCloud t = Tokenizer() def getInfo(url, link_list = []): res = req.urlopen(url) soup = BeautifulSoup(res, "html.parser") class_name = "side td1".strip() name_list = soup.find_all("td", class_ = class_name) for name in name_list: s = BeautifulSoup(str(name), "html.parser") link_list.append("https://www.uta-net.com" + s.find("a")["href"]) return link_list def wakati(word_list = []): link_list = getInfo("https://www.uta-net.com/artist/7840/6/") for link in link_list: res = req.urlopen(link) soup = BeautifulSoup(res, "html.parser") kashi = soup.find_all("div", id = "kashi_area") for doc in kashi: tokens = t.tokenize(doc.text) for token in tokens: if token.part_of_speech.split(',')[0] == u"名詞" or (token.part_of_speech.split(',')[0] == u"動詞" and len(token.surface) > 2): word_list.append(token.surface) return word_list def wordcloud(): word_list = wakati() words = " ".join(word_list) fpath = '/usr/share/fonts/truetype/fonts-japanese-gothic.ttf' wordcloud = WordCloud(background_color="white", font_path=fpath, width=900, height=500).generate(words) plt.figure(figsize=(15,12)) plt.imshow(wordcloud) plt.axis("off") plt.show() wordcloud.to_file('wordcloud.png') create_wordcloud()
結果
R言語についてのメモ
変数と配列
>hoge ← 値 >hoge ← c(値1,値2,…)
値を出力
>hoge
csvファイルの読み込み
>read.csv(hoge)
散布図を描く
>ggplot(csvを格納した変数) + geom_point(aes(x = x軸となる属性(変数), y = y軸となる属性(変数)))
回帰直線(単回帰)を描く
>library(ggplot2) >ggplot(csvを格納した変数) + geom_smooth(aes(x = x軸となる属性(変数), y = y軸となる属性(変数)), method="lm")
回帰直線の式
>csvを格納した変数.lm <- lm(y軸変数名~x軸変数名, data = csvを格納した変数) >csvを格納した変数.lm
pythonでCDのタイトルから曲名を取得する 2
やりたかったことについてはこちらを参照。
加えて今回はID3タグも編集してみる。
# -*- coding: utf-8 -*- #曲名を取得 from bs4 import BeautifulSoup import urllib.request as req import re import os from natsort import natsorted from mutagen.id3 import ID3, TPE1, TALB, TIT2, ID3NoHeaderError #収録曲を取得 def getInfo(cdtitle, name_list = []): list = [] artist_list = [] title_list = [] res = req.urlopen("https://www.oricon.co.jp/search/result.php?types=cd&search_string=" + cdtitle) soup = BeautifulSoup(res, "html.parser") links = soup.find_all("a") i = 1 for link in links: if "products" in link["href"]: res = req.urlopen("https://www.oricon.co.jp/" + link["href"]) page = BeautifulSoup(res, "html.parser") #オリコンニュースの部分を消したい page_title = page.title.text[:-13] page_title = page_title.replace("|", "/") list.append(str(i) + " " + page_title) artist = page.find("a", class_="artist-link") artist_list.append(artist) title = page.find_all("div", class_ = "music-title") title_list.append(title) i += 1 print(list) i = input("一致するものの番号を選択>>") name_list = title_list[int(i) - 1] #収録曲リストの末尾にアーティストの名前を追加 name_list.append(artist_list[int(i) - 1]) return name_list #音楽ファイルの曲情報を編集する def set_filename(): inputtitle = input("CDのタイトルを入力。空白がある場合は半角の「-」を入力>>") name_list = getInfo(inputtitle) list = [] musicname = "" for name in name_list: print(name.text) if name != name_list[-1]: for string in name.text[3:]: musicname += string list.append(musicname) musicname = "" else: list.append(name.text) print("同じフォルダに対してこのプログラムを複数回実行すると、データが消える可能性があります。") dirpath = input("フォルダのパスを入力>>") files = os.listdir(dirpath) files = sorted(files) i = 0 for musicfile in files: try: tags = ID3(dirpath + "/" + musicfile, v2_version=3) #TPE1 -> アーティスト tags.add(TPE1(encding = 3, text = list[-1])) #TALB -> アルバムタイトル inputtitle = inputtitle.replace("-", " ") tags.add(TALB(encoding = 3, text = inputtitle)) #TIT2 -> 曲のタイトル tags.add(TIT2(encoding = 3, text = list[i])) except ID3NoHeaderError: tags = ID3(v2_version=3) tags.save(dirpath + "/" + musicfile) print(tags) os.rename(dirpath + "/" + musicfile, dirpath + "/" + list[i]) i += 1 set_filename()
rubyでニュースを取得する
require 'open-uri' require 'nokogiri' def getInfo(url) charset = nil html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath("//li[@class='hasImg']").each do |ele| p ele.css("h3").text p ele.css("a")[0][:href] end end category_list = ["dom", "world", "eco"] for category in category_list url = "http://news.livedoor.com/topics/category/" + category + "/?p=" for i in 1..2 p i.to_s + "ページ目" getInfo(url + i.to_s) end end
pythonで価格.comから情報を取得する
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import urllib.parse import urllib.request as req import re f = open("result.txt", "w") page_list = [1,2,3] def scraping(page_count): print(str(page_count) + "ページ目") url = "https://kakaku.com/search_results/%97%E2%91%A0%8C%C9/?page=" + str(page_count) res = req.urlopen(url) soup = BeautifulSoup(res, "html.parser") #headとjavascript部分を削除 [s.decompose() for s in soup('script')] [s.decompose() for s in soup('head')] url_parts = soup.find_all("a") url_list = [] for url in url_parts: if "/?lid=pc_ksearch_kakakuitem" in url["href"]: url_list.append(url["href"]) soup = soup.text.replace("\n","") html_list = soup.split() #15~18 del html_list[:18] count = 0 for ele in html_list: if ele == "※": break elif "発売日" in ele: f.write(url_list[count] + "\n") f.write(ele + '\n') count += 2 else: f.write(ele + '\n') if page_count < max(page_list): choices = input("続行しますか?(yes or other key)>>") if not choices == "yes": return for i in page_list: scraping(i) f.close()
参考にした書籍
Pythonによるスクレイピング&機械学習 開発テクニック BeautifulSoup,scikit-learn,TensorFlowを使ってみよう
- 作者: クジラ飛行机
- 出版社/メーカー: ソシム
- 発売日: 2016/12/06
- メディア: 単行本
- この商品を含むブログ (4件) を見る
pythonでCDタイトルから曲名を取得する
ORICON NEWS|最新情報を発信する総合トレンドメディア をスクレイピングしてCDの情報を取得する。
コード
# -*- coding: utf-8 -*- #曲名を取得 from natsort import natsorted import os from bs4 import BeautifulSoup import urllib.request as req list = [] title = input("title>>") #フォルダ名を取得 dirname = os.path.basename(パス + title) #指定したフォルダの中にあるファイル名をリストで取得 dirfile = os.listdir(パス + title) #ファイルをソート dirfile = sorted(dirfile) cdtitle = dirname.replace(" ", "+") res = req.urlopen("https://www.oricon.co.jp/search/result.php?types=cd&search_string=" + cdtitle) soup = BeautifulSoup(res, "html.parser") text = soup.find_all("a") for string in text: if dirname in string.text: res = req.urlopen("https://www.oricon.co.jp" + string.attrs['href']) soup = BeautifulSoup(res, "html.parser") #曲名のリスト text = soup.find_all("div", class_="music-title") if (len(dirfile)) == len(text): for string in text: list.append(string.text) break i = 0 for name in dirfile: #ファイル名を書き換える os.rename(パス" + title + "/" + name, パス + title + "/" + list[i]) i = i + 1
CDのタイトルは「I beg you」を入力する。
実行前
実行後
pythonでNAVITIMEの電車混雑リポートから混み具合を取得する
beautifulsoupを用いたスクレイピングをしてみた。
#-*- coding: utf-8 -*- #混雑状況 from bs4 import BeautifulSoup import urllib.request as req import re url_list = ["https://www.navitime.co.jp/train/00000132/%EF%BC%AA%EF%BC%B2%E4%BA%AC%E8%91%89%E7%B7%9A_%EF%BC%AA%EF%BC%B2%E6%AD%A6%E8%94%B5%E9%87%8E%E7%B7%9A?nodeId=00007548", "https://www.navitime.co.jp/train/00000183/%EF%BC%AA%EF%BC%B2%E6%9D%B1%E6%B5%B7%E9%81%93%E6%9C%AC%E7%B7%9A%28%E6%9D%B1%E4%BA%AC-%E7%86%B1%E6%B5%B7%29?nodeId=00006668", "https://www.navitime.co.jp/train/00000123/%E6%A8%AA%E9%A0%88%E8%B3%80%E7%B7%9A?nodeId=00007965", "https://www.navitime.co.jp/train/00000168/%E7%B7%8F%E6%AD%A6%E7%B7%9A%E5%BF%AB%E9%80%9F/?nodeId=00000491" ] list = ["京葉線&武蔵野線","東海道本線","横須賀線","総武快速線"] print("ユーザーからの投稿") i = 0 for url in url_list: res = req.urlopen(url) soup = BeautifulSoup(res, "html.parser") html = soup.find_all("div") for h in html: if h.string == "※混雑リポートを最大3件まで新着順で表示しております。": print(list[i]) print(" ") i = i + 1 break else: h_string = str(h.string) byte_h = h_string.encode() #文字列=>byte if len(byte_h) > 4: #Noneを削除 print(h.string)