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

言語処理100本ノック

37. 頻度上位10語¶

出現頻度が高い10語とその出現頻度をグラフ(例えば棒グラフなど)で表示せよ.

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
X = range(10)
Y = []
for y in list[:10]:
    Y.append(y[1])
plt.bar(X,Y)
plt.show()

f:id:bitop:20161231105657p:plain

言語処理100本ノック

36. 単語の出現頻度

文章中に出現する単語とその出現頻度を求め,出現頻度の高い順に並べよ.

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)]
for k, v in list:
    print(k, v)

<結果 一部>

の 9194
。 7486
て 6868
、 6772
は 6420
に 6243
を 6071
と 5508
が 5337
た 3988
で 3806
「 3231
」 3225
も 2479
ない 2390
だ 2363
し 2322
から 2032
ある 1728

言語処理100本ノック

35. 名詞の連接

名詞の連接(連続して出現する名詞)を最長一致で抽出せよ

import re

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()

rensetu = []
for sentence in sentences:
    for index in range(0,len(sentence)):
        if sentence[index]["pos"] == "名詞":
            rensetu.append(sentence[index]["surface"])
        else:
            if len(rensetu) > 1:
                print(rensetu)
            rensetu = []

 <結果 一部>
['人間', '中']
['一番', '獰悪']
['時', '妙']
['一', '毛']
['その後', '猫']
['一', '度']
['ぷうぷうと', '煙']
['邸', '内']
['三', '毛']
['書生', '以外']
['四', '五', '遍']
['この間', 'おさん']