Created
December 19, 2008 07:54
-
-
Save javascripter/37913 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name MarkovLDR | |
// @namespace http://d.hatena.ne.jp/javascripter/ | |
// @include http://reader.livedoor.com/reader/ | |
// @require http://chasen.org/~taku/software/TinySegmenter/tiny_segmenter-0.1.js | |
// ==/UserScript== | |
function Markov() { | |
this._dic = {}; | |
this._segment = null; | |
} | |
Markov.prototype.make = function (source) { | |
var segmenter = new TinySegmenter(); | |
var ary = this._segment = segmenter.segment(source); | |
var dic = this._dic; | |
for (var i = 0, l = ary.length; i < l; ++i) { | |
var word = ary[i % l]; | |
var next = ary[(i + 1) % l]; | |
if (word in dic) { | |
dic[word].push(next); | |
} else { | |
dic[word] = [next]; | |
} | |
} | |
return this; | |
}; | |
Markov.prototype.take = function (size) { | |
var ary = this._segment; | |
var dic = this._dic; | |
if (!size) { | |
size = ary.length; | |
} | |
function pickup(ary) { | |
return ary[Math.floor(Math.random() * ary.length)]; | |
} | |
var ret = []; | |
var current = ary; | |
for (var i = 0; i < size; ++i) { | |
var s = pickup(current); | |
ret.push(s); | |
current = dic[s] | |
} | |
return ret.join(''); | |
}; | |
with (unsafeWindow) { | |
LDR.register_hook('before_printfeed', function (feed) { | |
if (feed._markov) return feed; | |
feed._markov = true; | |
feed.items.forEach(function (item) { | |
if (Math.random() < 0.5) return; | |
item.title += ' (Markov)'; | |
var div = document.createElement('div'); | |
div.innerHTML = item.body; | |
item.body = new Markov().make(div.textContent).take(); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment