pythonのソースコードを調べる

Cファイルからインクルードしているヘッダファイルを調べる

def iter_docs(file):
    """
    指定したCファイルにインクルードされているヘッダファイルを返す
    """
    for line in file:
        if line.startswith("#include"):
            #include文に続くヘッダファイル名を抜き出す
            m = re.search(r'\".*\"',line)
            if m != None:
                yield m.group().strip("\"").split("/")[-1]

def get_hlist(path_name):
    """
    指定されたCファイルのpath_nameをもらってそのCファイルにインクルード
    されているヘッダファイルファイルをリストにして返す。
    """
    h_file_list = []
    for path in path_name:
        with open(path) as f:
            for hf in iter_docs(f):
                h_file_list.append(hf)
    h_file_list = list(set(h_file_list))
    print("--head file---------------")
    print("上位10位まで表示")
    for v in h_file_list[:10]:
        print(v)
    print("len=",len(h_file_list))
    return h_file_list


    <結果>
    最初10行まで表示
    sha256module.c.h
    unicodedefs.h
    mappings_hk.h
    ucs4lib.h
    datetime.h
    code.h
    grammar.h
    rotatingtree.h
    fileobject.h
    float.h

pythonのソースコードを調べる

ファイル内の単語頻度をしらべる

def freqdist_count(path_name):
    """
    指定したpath_nameを読み込んで、そのテキスト内単語の頻度を表示する
    """
    count_dic = {}
    for path in path_name[:]:
        with open(path,"r") as f:
            text = f.read() 
            #コメントを削除(複数行も削除)
            text = re.sub(r"/\*([^*]|\*[^/])*\*/","",text)
            #{} ()を空白に置き換える
            text = re.sub(r"\("," ",text)
            text = re.sub(r"\)"," ",text)
            text = re.sub(r"{"," ",text)
            text = re.sub(r"}"," ",text)
            #単独の数値を空白に置き換える
            text = re.sub(r"[0-9]+"," ", text)
            #カンマを空白に置き換える
            text = re.sub(r"\,"," ",text)
            #;を空白に置き換える
            text = re.sub(r";"," ",text)
            wList = text.split()
            for w in wList:
                if w in c_lang_keyword:
                    continue
                count_dic[w] = count_dic.get(w,0) + 1
    count_list= sorted(count_dic.items(), key=lambda x: x[1],reverse=True)
    print("--freqdist---------------")
    print("上位10位まで表示")
    s = 0
    for k,v in count_list[:10]:
        print(k,":",v)
        s += v        
    print("{:,}".format(s)

    path_name = count_file_func(c_file_list)
    freqdist_count(path_name)

    <結果>
   上位10位まで表示
    PyObject : 12235
    \ : 3648
    Py_DECREF : 3485
    Py_ssize_t : 3052
    self : 3048
    c : 2699
    res : 2572
    len : 1922
    " : 1815
    value : 1693
    36,169

最頻度はPyObjectで、これが最重要データ構造と思われる。

pythonのソースコードを調べる

179のファイルがどのフォルダーに分布しているのか調べた。

import glob
import os

c_file_list = ["_bisectmodule.c","_codecsmodule.c","_collectionsmodule.c","_csv.c",
"_functoolsmodule.c","_heapqmodule.c","_json.c","_localemodule.c",
"_lsprof.c","_math.c","_pickle.c","_randommodule.c","_sre.c","_stat.c",
"_struct.c","_weakref.c","arraymodule.c","atexitmodule.c","audioop.c",
"binascii.c","cmathmodule.c","_datetimemodule.c","errnomodule.c",
"faulthandler.c","gcmodule.c","hashtable.c","itertoolsmodule.c",
"main.c","mathmodule.c","md5module.c","mmapmodule.c","_opcode.c",
"_operator.c","parsermodule.c","posixmodule.c","rotatingtree.c",
"sha1module.c","sha256module.c","sha512module.c","signalmodule.c",
"symtablemodule.c","_threadmodule.c","_tracemalloc.c","timemodule.c",
"xxsubtype.c","zipimport.c","zlibmodule.c","fileio.c","bytesio.c",
"stringio.c","bufferedio.c","iobase.c","textio.c","_iomodule.c","adler32.c",
"compress.c","crc32.c","deflate.c","infback.c","inffast.c","inflate.c","inftrees.c",
"trees.c","uncompr.c","zutil.c","_codecs_cn.c","_codecs_hk.c","_codecs_iso2022.c",
"_codecs_jp.c","_codecs_kr.c","_codecs_tw.c","multibytecodec.c","_winapi.c",
"abstract.c","accu.c","boolobject.c","bytes_methods.c","bytearrayobject.c",
"bytesobject.c","capsule.c","cellobject.c","classobject.c","codeobject.c",
"complexobject.c","descrobject.c","dictobject.c","enumobject.c","exceptions.c",
"fileobject.c","floatobject.c","frameobject.c","funcobject.c","genobject.c",
"iterobject.c","listobject.c","longobject.c","memoryobject.c","methodobject.c",
"moduleobject.c","namespaceobject.c","object.c","obmalloc.c","odictobject.c",
"rangeobject.c","setobject.c","sliceobject.c","structseq.c","tupleobject.c",
"typeobject.c","unicodectype.c","unicodeobject.c","weakrefobject.c",
"acceler.c","bitset.c","firstsets.c","grammar.c","grammar1.c","listnode.c",
"metagrammar.c","myreadline.c","node.c","parser.c","parsetok.c","tokenizer.c",
"invalid_parameter_handler.c","winreg.c","config.c","getpathp.c","msvcrtmodule.c",
"pyhash.c","random.c","_warnings.c","asdl.c","ast.c","bltinmodule.c","ceval.c",
"codecs.c","compile.c","dynamic_annotations.c","dynload_win.c","errors.c",
"fileutils.c","formatter_unicode.c","frozen.c","future.c","getargs.c",
"getcompiler.c","getcopyright.c","getopt.c","getplatform.c","getversion.c",
"graminit.c","import.c","importdl.c","marshal.c","modsupport.c","mysnprintf.c",
"mystrtoul.c","peephole.c","pyarena.c","pyctype.c","pyfpe.c","pylifecycle.c",
"pymath.c","pytime.c","pystate.c","pystrcmp.c","pystrhex.c","pystrtod.c","dtoa.c",
"Python-ast.c","pythonrun.c","structmember.c","symtable.c","sysmodule.c",
"thread.c","traceback.c","dl_nt.c","getbuildinfo.c"]
path_name = []
file_name = []
dir_name = []
dir_count = dict(zip(['Modules\\zlib', 'Parser', 'Modules\\_io', 'Python', 'Objects', 'Modules', 'Modules\\cjkcodecs', 'PC'],[0,0,0,0,0,0,0,0]))
for p in glob.glob("**",recursive =True):
    if p.split(".")[-1] != "c":
        continue
    base_name = os.path.basename(p)
    parent_name = os.path.split(p)[0]
    if base_name in c_file_list:
        path_name.append(p)
        dir_name.append(parent_name)
        file_name.append(base_name)
        dir_count[parent_name] += 1
#targetとなっているファイルが所属するデリクトリの集約とそのデリクトリに所属するファイル数の計上    
for key in dir_count:
    print(key,dir_count[key])


<結果>
Objects 39
Modules\_io 7
Parser 12
Modules\zlib 11
Modules\cjkcodecs 7
Python 48
PC 6
Modules 49
Modules フォルダーが一番多く、次がPythonフォルダーが続く。  

pythonのソースコードを調べる

python.org.download/sourceでpython 3.5.3rc1 2017-01-03をダウンロード
デリクトリ構造

D:.
├─Doc
│  ├─c-api
│  ├─data
│  ├─distributing
│  ├─distutils
│  ├─extending
│  ├─faq
│  ├─howto
│  ├─includes
│  │  └─sqlite3
│  ├─install
│  ├─installing
│  ├─library
│  ├─reference
│  ├─tools
│  │  ├─extensions
│  │  ├─pydoctheme
│  │  │  └─static
│  │  ├─static
│  │  └─templates
│  ├─tutorial
│  ├─using
│  └─whatsnew
├─externals
│  └─openssl-1.0.2j
│      └─tmp
│          └─win32_Debug
│              ├─libeay
│              │  └─libeay.tlog
│              └─ssleay
│                  └─ssleay.tlog
├─Grammar
├─Include
├─Lib
│  ├─asyncio
│  ├─collections
│  ├─concurrent
│  │  └─futures
│  ├─ctypes
│  │  ├─macholib
│  │  ├─test
│  │  └─__pycache__
│  ├─curses
│  ├─dbm
│  ├─distutils
│  │  ├─command
│  │  └─tests
│  ├─email
│  │  └─mime
│  ├─encodings
│  │  └─__pycache__
│  ├─ensurepip
│  │  └─_bundled
│  ├─html
│  ├─http
│  ├─idlelib
│  │  ├─Icons
│  │  └─idle_test
│  ├─importlib
│  ├─json
│  ├─lib2to3
│  │  ├─fixes
│  │  ├─pgen2
│  │  └─tests
│  │      └─data
│  │          └─fixers
│  │              └─myfixes
│  ├─logging
│  ├─msilib
│  ├─multiprocessing
│  │  └─dummy
│  ├─plat-aix4
│  ├─plat-darwin
│  ├─plat-freebsd4
│  ├─plat-freebsd5
│  ├─plat-freebsd6
│  ├─plat-freebsd7
│  ├─plat-freebsd8
│  ├─plat-generic
│  ├─plat-linux
│  ├─plat-netbsd1
│  ├─plat-next3
│  ├─plat-sunos5
│  ├─plat-unixware7
│  ├─pydoc_data
│  ├─site-packages
│  ├─sqlite3
│  │  └─test
│  ├─test
│  │  ├─audiodata
│  │  ├─capath
│  │  ├─cjkencodings
│  │  ├─crashers
│  │  ├─data
│  │  ├─decimaltestdata
│  │  ├─eintrdata
│  │  ├─encoded_modules
│  │  ├─imghdrdata
│  │  ├─leakers
│  │  ├─sndhdrdata
│  │  ├─subprocessdata
│  │  ├─support
│  │  ├─test_asyncio
│  │  ├─test_email
│  │  │  └─data
│  │  ├─test_import
│  │  │  └─data
│  │  │      └─circular_imports
│  │  │          └─subpkg
│  │  ├─test_importlib
│  │  │  ├─builtin
│  │  │  ├─extension
│  │  │  ├─frozen
│  │  │  ├─import_
│  │  │  ├─namespace_pkgs
│  │  │  │  ├─both_portions
│  │  │  │  │  └─foo
│  │  │  │  ├─module_and_namespace_package
│  │  │  │  │  └─a_test
│  │  │  │  ├─not_a_namespace_pkg
│  │  │  │  │  └─foo
│  │  │  │  ├─portion1
│  │  │  │  │  └─foo
│  │  │  │  ├─portion2
│  │  │  │  │  └─foo
│  │  │  │  ├─project1
│  │  │  │  │  └─parent
│  │  │  │  │      └─child
│  │  │  │  ├─project2
│  │  │  │  │  └─parent
│  │  │  │  │      └─child
│  │  │  │  └─project3
│  │  │  │      └─parent
│  │  │  │          └─child
│  │  │  └─source
│  │  ├─test_json
│  │  ├─test_tools
│  │  ├─test_warnings
│  │  │  └─data
│  │  ├─tracedmodules
│  │  └─xmltestdata
│  ├─tkinter
│  │  └─test
│  │      ├─test_tkinter
│  │      └─test_ttk
│  ├─turtledemo
│  ├─unittest
│  │  └─test
│  │      └─testmock
│  ├─urllib
│  ├─venv
│  │  └─scripts
│  │      ├─nt
│  │      └─posix
│  ├─wsgiref
│  ├─xml
│  │  ├─dom
│  │  ├─etree
│  │  ├─parsers
│  │  └─sax
│  ├─xmlrpc
│  └─__pycache__
├─Mac
│  ├─BuildScript
│  │  ├─resources
│  │  └─scripts
│  ├─Icons
│  ├─IDLE
│  │  └─IDLE.app
│  │      └─Contents
│  │          ├─MacOS
│  │          └─Resources
│  ├─PythonLauncher
│  │  └─English.lproj
│  │      ├─MainMenu.nib
│  │      ├─MyDocument.nib
│  │      └─PreferenceWindow.nib
│  ├─Resources
│  │  ├─app
│  │  │  └─Resources
│  │  ├─framework
│  │  └─iconsrc
│  └─Tools
├─Misc
├─Modules
│  ├─cjkcodecs
│  │  └─clinic
│  ├─clinic
│  ├─expat
│  ├─zlib
│  ├─_ctypes
│  │  ├─darwin
│  │  ├─libffi
│  │  │  ├─doc
│  │  │  ├─include
│  │  │  ├─libffi.xcodeproj
│  │  │  ├─m4
│  │  │  ├─man
│  │  │  ├─src
│  │  │  │  ├─aarch64
│  │  │  │  ├─alpha
│  │  │  │  ├─arc
│  │  │  │  ├─arm
│  │  │  │  ├─avr32
│  │  │  │  ├─bfin
│  │  │  │  ├─cris
│  │  │  │  ├─frv
│  │  │  │  ├─ia64
│  │  │  │  ├─m32r
│  │  │  │  ├─m68k
│  │  │  │  ├─m88k
│  │  │  │  ├─metag
│  │  │  │  ├─microblaze
│  │  │  │  ├─mips
│  │  │  │  ├─moxie
│  │  │  │  ├─nios2
│  │  │  │  ├─pa
│  │  │  │  ├─powerpc
│  │  │  │  ├─s390
│  │  │  │  ├─sh
│  │  │  │  ├─sh64
│  │  │  │  ├─sparc
│  │  │  │  ├─tile
│  │  │  │  ├─vax
│  │  │  │  ├─x86
│  │  │  │  └─xtensa
│  │  │  └─testsuite
│  │  │      ├─config
│  │  │      ├─lib
│  │  │      └─libffi.call
│  │  ├─libffi_arm_wince
│  │  ├─libffi_msvc
│  │  └─libffi_osx
│  │      ├─include
│  │      ├─powerpc
│  │      └─x86
│  ├─_decimal
│  │  ├─libmpdec
│  │  │  └─literature
│  │  └─tests
│  ├─_io
│  │  └─clinic
│  ├─_multiprocessing
│  └─_sqlite
├─Objects
│  ├─clinic
│  └─stringlib
├─Parser
├─PC
│  ├─bdist_wininst
│  └─clinic
├─PCbuild
│  ├─.ipynb_checkpoints
│  ├─Debug
│  ├─obj
│  │  ├─win32_Debug
│  │  │  ├─bdist_wininst
│  │  │  │  └─bdist_wininst.tlog
│  │  │  ├─pyexpat
│  │  │  │  └─pyexpat.tlog
│  │  │  ├─pylauncher
│  │  │  │  └─pylauncher.tlog
│  │  │  ├─pyshellext
│  │  │  │  └─pyshellext.tlog
│  │  │  ├─python
│  │  │  │  └─python.tlog
│  │  │  ├─python3dll
│  │  │  │  └─python3dll.tlog
│  │  │  ├─pythoncore
│  │  │  │  └─pythoncore.tlog
│  │  │  ├─pythonw
│  │  │  │  └─pythonw.tlog
│  │  │  ├─pywlauncher
│  │  │  │  └─pywlauncher.tlog
│  │  │  ├─select
│  │  │  │  └─select.tlog
│  │  │  ├─sqlite3
│  │  │  │  └─sqlite3.tlog
│  │  │  ├─tcl
│  │  │  ├─tix
│  │  │  ├─tk
│  │  │  ├─unicodedata
│  │  │  │  └─unicodedata.tlog
│  │  │  ├─winsound
│  │  │  │  └─winsound.tlog
│  │  │  ├─_bz2
│  │  │  │  └─_bz2.tlog
│  │  │  ├─_ctypes
│  │  │  │  └─_ctypes.tlog
│  │  │  ├─_ctypes_test
│  │  │  │  └─_ctypes_test.tlog
│  │  │  ├─_decimal
│  │  │  │  └─_decimal.tlog
│  │  │  ├─_elementtree
│  │  │  │  └─_elementtree.tlog
│  │  │  ├─_freeze_importlib
│  │  │  │  └─_freeze_.19C0C13F.tlog
│  │  │  ├─_hashlib
│  │  │  │  └─_hashlib.tlog
│  │  │  ├─_lzma
│  │  │  │  └─_lzma.tlog
│  │  │  ├─_msi
│  │  │  │  └─_msi.tlog
│  │  │  ├─_multiprocessing
│  │  │  │  └─_multiprocessing.tlog
│  │  │  ├─_overlapped
│  │  │  │  └─_overlapped.tlog
│  │  │  ├─_socket
│  │  │  │  └─_socket.tlog
│  │  │  ├─_sqlite3
│  │  │  │  └─_sqlite3.tlog
│  │  │  ├─_ssl
│  │  │  │  └─_ssl.tlog
│  │  │  ├─_testbuffer
│  │  │  │  └─_testbuffer.tlog
│  │  │  ├─_testcapi
│  │  │  │  └─_testcapi.tlog
│  │  │  ├─_testembed
│  │  │  │  └─_testembed.tlog
│  │  │  ├─_testimportmultiple
│  │  │  │  └─_testimp.36D0C52C.tlog
│  │  │  ├─_testmultiphase
│  │  │  │  └─_testmultiphase.tlog
│  │  │  └─_tkinter
│  │  │      └─_tkinter.tlog
│  │  └─win32_Release
│  │      └─xxlimited
│  │          └─xxlimited.tlog
│  └─win32
├─Programs
├─Python
│  └─clinic
└─Tools
    ├─buildbot
    ├─ccbench
    ├─clinic
    ├─demo
    ├─freeze
    │  └─test
    ├─gdb
    ├─hg
    ├─i18n
    ├─importbench
    ├─iobench
    ├─msi
    │  ├─bundle
    │  │  ├─bootstrap
    │  │  └─packagegroups
    │  ├─core
    │  ├─dev
    │  ├─doc
    │  ├─exe
    │  ├─launcher
    │  ├─lib
    │  ├─path
    │  ├─pip
    │  ├─tcltk
    │  ├─test
    │  └─tools
    ├─nuget
    ├─parser
    ├─pybench
    │  └─package
    ├─pynche
    │  └─X
    ├─scripts
    ├─ssl
    ├─stringbench
    ├─test2to3
    │  ├─test
    │  └─test2to3
    ├─unicode
    │  └─python-mappings
    └─unittestgui

D:\Python-3.5.3rc1> 調べる対象をpython.coreに限定 対象cファイルは179個

_bisectmodule.c
_codecsmodule.c
_collectionsmodule.c
_csv.c
_functoolsmodule.c
_heapqmodule.c
_json.c
_localemodule.c
_lsprof.c
_math.c
_pickle.c
_randommodule.c
_sre.c
_stat.c
_struct.c
_weakref.c
arraymodule.c
atexitmodule.c
audioop.c
binascii.c
cmathmodule.c
_datetimemodule.c
errnomodule.c
faulthandler.c
gcmodule.c
hashtable.c
itertoolsmodule.c
main.c
mathmodule.c
md5module.c
mmapmodule.c
_opcode.c
_operator.c
parsermodule.c
posixmodule.c
rotatingtree.c
sha1module.c
sha256module.c
sha512module.c
signalmodule.c
symtablemodule.c
_threadmodule.c
_tracemalloc.c
timemodule.c
xxsubtype.c
zipimport.c
zlibmodule.c
fileio.c
bytesio.c
stringio.c
bufferedio.c
iobase.c
textio.c
_iomodule.c
adler32.c
compress.c
crc32.c
deflate.c
infback.c
inffast.c
inflate.c
inftrees.c
trees.c
uncompr.c
zutil.c
_codecs_cn.c
_codecs_hk.c
_codecs_iso2022.c
_codecs_jp.c
_codecs_kr.c
_codecs_tw.c
multibytecodec.c
_winapi.c
abstract.c
accu.c
boolobject.c
bytes_methods.c
bytearrayobject.c
bytesobject.c
capsule.c
cellobject.c
classobject.c
codeobject.c
complexobject.c
descrobject.c
dictobject.c
enumobject.c
exceptions.c
fileobject.c
floatobject.c
frameobject.c
funcobject.c
genobject.c
iterobject.c
listobject.c
longobject.c
memoryobject.c
methodobject.c
moduleobject.c
namespaceobject.c
object.c
obmalloc.c
odictobject.c
rangeobject.c
setobject.c
sliceobject.c
structseq.c
tupleobject.c
typeobject.c
unicodectype.c
unicodeobject.c
weakrefobject.c
acceler.c
bitset.c
firstsets.c
grammar.c
grammar1.c
listnode.c
metagrammar.c
myreadline.c
node.c
parser.c
parsetok.c
tokenizer.c
invalid_parameter_handler.c
winreg.c
config.c
getpathp.c
msvcrtmodule.c
pyhash.c
random.c
_warnings.c
asdl.c
ast.c
bltinmodule.c
ceval.c
codecs.c
compile.c
dynamic_annotations.c
dynload_win.c
errors.c
fileutils.c
formatter_unicode.c
frozen.c
future.c
getargs.c
getcompiler.c
getcopyright.c
getopt.c
getplatform.c
getversion.c
graminit.c
import.c
importdl.c
marshal.c
modsupport.c
mysnprintf.c
mystrtoul.c
peephole.c
pyarena.c
pyctype.c
pyfpe.c
pylifecycle.c
pymath.c
pytime.c
pystate.c
pystrcmp.c
pystrhex.c
pystrtod.c
dtoa.c
Python-ast.c
pythonrun.c
structmember.c
symtable.c
sysmodule.c
thread.c
traceback.c
dl_nt.c
getbuildinfo.c

言語処理100本ノック

40. 係り受け解析結果の読み込み(形態素

形態素を表すクラスMorphを実装せよ.このクラスは表層形(surface),基本形(base),品詞(pos),品詞細分類1(pos1)をメンバ変数に持つこととする.さらに,CaboChaの解析結果(neko.txt.cabocha)を読み込み,各文をMorphオブジェクトのリストとして表現し,3文目の形態素列を表示せよ.

import MeCab
import CaboCha
import re

class Morph:
    def __init__(self,surface,base,pos,pos1):
        self.surface = surface  #表層形
        self.base = base  #基本形
        self.pos = pos  #品詞
        self.pos1 = pos1  #品詞細分類1

def parse_neko(in_text_name,out_text_name):
    c = CaboCha.Parser()
    with open(out_text_name,mode="w") as out_text:
        with open(in_text_name) as in_text:
            for line in in_text:
                tree = c.parse(line)
                out_text.write(tree.toString(CaboCha.FORMAT_LATTICE))

#parse_neko("./neko.txt","./neko.txt.cabocha")
sent = []
text = []
with open("./neko.txt.cabocha") as parse_text:
    for line in parse_text:
        if line == "EOS\n":
            text.append(sent)
            sent = []
        else:
            if line[0] == "*":
                continue
            line = line.rstrip()
            word = re.split(r"[\t,]",line)
            sent.append(Morph(word[0],word[7],word[1],word[2]))
for word in text[2]:
    print(word.surface)


<結果>

吾輩
は
猫
で
ある
。

言語処理100本ノック

39. Zipfの法則

単語の出現頻度順位を横軸,その出現頻度を縦軸として,両対数グラフをプロットせよ.

%matplotlib inline
import re
from collections import Counter

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

word_count = {}
for sentence in sentences:
    for index in range(0,len(sentence)):
        item = sentence[index]["surface"]
        if item in word_count:
            word_count[item] += 1
        else:
            word_count[item] = 1
list = [(k, word_count[k]) for k in sorted(word_count, key=word_count.get, reverse=True)]

import matplotlib.pyplot as plt
Y = []
for y in list:
    Y.append(y[1])
plt.loglog(range(len(Y)),Y)
plt.show()

f:id:bitop:20170109140642p:plain

言語処理100本ノック

38. ヒストグラム

単語の出現頻度のヒストグラム(横軸に出現頻度,縦軸に出現頻度をとる単語の種類数を棒グラフで表したもの)を描け.

%matplotlib inline
import re
from collections import Counter

sentences = []
with open("D:\\nlp100\\neko.txt.mecab",encoding="UTF-8") as fr:
    line = fr.readline()
    keitaiso = []
    while line:
        if "EOS" in line:
            if len(keitaiso)>0:
                sentences.append(keitaiso)
                keitaiso = []
        else:
            line = re.split(r'[\t,]',line)            
            keitaiso.append({"surface":line[0],"base":line[7],"pos":line[1],"pos1":line[2]})
        line =fr.readline()

word_count = {}
for sentence in sentences:
    for index in range(0,len(sentence)):
        item = sentence[index]["surface"]
        if item in word_count:
            word_count[item] += 1
        else:
            word_count[item] = 1
list = [(k, word_count[k]) for k in sorted(word_count, key=word_count.get, reverse=True)]

import matplotlib.pyplot as plt
Y = []
for y in list:
    Y.append(y[1])
plt.hist(Y,bins=20,range=(1, 20))
plt.show()

<結果>

f:id:bitop:20170108161758p:plain