Help us understand the problem. What is going on with this article?

Pythonで分かち書きを自作する(英文)

More than 1 year has passed since last update.

環境

Python 3.5.6 | Anaconda
Jupyter Notebook
Windows 10

やりたいこと

おそらく形態素解析のライブラリはあると思うが、勉強のために英単語の出現回数をカウントするコードを自作したい。

車輪の再発明どんとこい。

参考にした情報

みんなのPython 第4版
辞書を値でソートする
対象データ

コード

LeavingSpaceBetweenWords.py
# 形態素解析したいデータを格納し、ピリオドを半角スペースへ置換
line_source = 'WASHINGTON — Senior Pentagon officials are voicing deepening fears that President Trump’s hawkish national security adviser, John R. Bolton, could precipitate a conflict with Iran at a time when Mr. Trump is losing leverage in the Middle East by pulling out American troops.'
line = line_source.replace(".", " ")
wordcount = dict()

# 半角スペースで分かち書いて変数に格納
# ディクショナリのキー(=変数)に存在すればカウントアップ、なければキーと値に登録
for word in line.split():
    if word in wordcount:
        wordcount[word] = wordcount[word] + 1
    else:
        wordcount.update({word : 1})

# 出現頻度の降順でソートし出力
for k, v in sorted(wordcount.items(), key=lambda x: x[1], reverse=True):
    print(k, v)
#     出現単語が多いときは閾値によって出力を制御
#     if v >= 5:
#         print(k, v)

出力結果

a 2
WASHINGTON 1
— 1
Senior 1
Pentagon 1
officials 1
are 1
voicing 1
deepening 1
fears 1
that 1
President 1
Trump’s 1
hawkish 1
national 1
security 1
adviser, 1
John 1
R 1
Bolton, 1
could 1
precipitate 1
conflict 1
with 1
Iran 1
at 1
time 1
when 1
Mr 1
Trump 1
is 1
losing 1
leverage 1
in 1
the 1
Middle 1
East 1
by 1
pulling 1
out 1
American 1
troops 1

やり残し

  • 対象のデータはcsvを読み込む形式とか、任意のWebページをスクレイピングしてデータを取得、なんかもできるんだろうなー
  • 出現頻度のグラフ化はそのうちやる
  • 自作では日本語の形態素解析は辞書データないと無理め
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away