Skip to content

Instantly share code, notes, and snippets.

@sorah
Created April 12, 2009 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sorah/93815 to your computer and use it in GitHub Desktop.
Save sorah/93815 to your computer and use it in GitHub Desktop.
日本語用 形態素解析もどき+マルコフ連鎖
#日本語用 形態素解析もどき
#http://ablog.seesaa.net/article/24578324.html
#を移植したものです。とりあえずライセンスは、Creative commonsの表示で。商用利用OKですが、自分の名前を明記してください。
#クレジット:sorah 感謝:http://ablog.seesaa.net/article/24578324.html
#str=形態素解析したい文字列(日本語のみ)
#返却するのは分割された配列。
def morphAnalyzer(str)
s = str.gsub(/([一-龠々〆ヵヶ]+|[ぁ-ん]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+|[,.、。!!??()()「」『』]+|[  ]+)/,"\\1|")
ary = s.split("|")
result = [];
ary.each_index {|i|
token = ary[i].match(/(でなければ|について|ならば|までを|までの|くらい|なのか|として|とは|なら|から|まで|して|だけ|より|ほど|など|って|では|は|で|を|の|が|に|へ|と|て)/).to_a
if token
token.each{|n|
result.push(n)
}
end
}
end
#マルコフ連鎖で文の生成
#str=素材にする文章(文の終わりにはかならず「。」をつけること)
#返却=生成された文章
def markovChainSentence(str)
dic = {}
if str
s = str.split("。")
s.each_index {|i|
if s[i]
makeMarkovToken(s[i]+"。",dic)
end
}
return markovChain(dic)
end
end
def makeMarkovToken(str,dic)
token = morphAnalyzer(str)
token.unshift('_START_')
token.push('_END_')
while token[1]
if dic[token[0]]
dic[token[0]].push(token[1])
else
dic[token[0]] = [token[1]]
end
token.shift()
end
end
#マルコフ連鎖で使用するメソッド
def markovChain(dic)
w1 = dic['_START_'][(rand()*dic['_START_'].length).floor]#
w2 = ''
sentence = w1
200.times do
w2 = dic[w1][(rand()*dic[w1].length).floor]
if w2 == '_END_'
break
end
sentence += w2
w3 = w1
w1 = w2
w2 = w3
end
return sentence
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment