Topic:
A code snippet that analyzes a user's favorite book quotes and writing style to generate personalized creative writing prompts and story starters tailored to their literary preferences and narrative voice.
Snippet:
<pre class="hljs language-python"><code class="hljs language-python"><span class="hljs-keyword">import</span> nltk
<span class="hljs-keyword">from</span> nltk.tokenize <span class="hljs-keyword">import</span> word_tokenize, sent_tokenize
<span class="hljs-keyword">from</span> nltk.corpus <span class="hljs-keyword">import</span> stopwords
<span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> Counter
<span class="hljs-keyword">import</span> random
nltk.download(<span class="hljs-string">'punkt'</span>)
nltk.download(<span class="hljs-string">'stopwords'</span>)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">analyze_quotes</span>(<span class="hljs-params">quotes</span>):
words = [word.lower() <span class="hljs-keyword">for</span> quote <span class="hljs-keyword">in</span> quotes <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> word_tokenize(quote)]
words = [word <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> words <span class="hljs-keyword">if</span> word.isalnum() <span class="hljs-keyword">and</span> word <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> stopwords.words(<span class="hljs-string">'english'</span>)]
<span class="hljs-keyword">return</span> Counter(words)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">analyze_style</span>(<span class="hljs-params">quotes</span>):
sentences = [sent <span class="hljs-keyword">for</span> quote <span class="hljs-keyword">in</span> quotes <span class="hljs-keyword">for</span> sent <span class="hljs-keyword">in</span> sent_tokenize(quote)]
avg_length = <span class="hljs-built_in">sum</span>(<span class="hljs-built_in">len</span>(sent.split()) <span class="hljs-keyword">for</span> sent <span class="hljs-keyword">in</span> sentences) / <span class="hljs-built_in">len</span>(sentences)
complex_sentences = <span class="hljs-built_in">sum</span>(<span class="hljs-number">1</span> <span class="hljs-keyword">for</span> sent <span class="hljs-keyword">in</span> sentences <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(sent.split()) > <span class="hljs-number">20</span>)
<span class="hljs-keyword">return</span> {
<span class="hljs-string">'avg_sentence_length'</span>: avg_length,
<span class="hljs-string">'complex_sentence_ratio'</span>: complex_sentences / <span class="hljs-built_in">len</span>(sentences)
}
<span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_prompt</span>(<span class="hljs-params">word_freq, style</span>):
themes = [word <span class="hljs-keyword">for</span> word, _ <span class="hljs-keyword">in</span> word_freq.most_common(<span class="hljs-number">5</span>)]
<span class="hljs-keyword">if</span> style[<span class="hljs-string">'avg_sentence_length'</span>] > <span class="hljs-number">15</span>:
structure = <span class="hljs-string">"complex, winding sentences"</span>
<span class="hljs-keyword">else</span>:
structure = <span class="hljs-string">"short, punchy sentences"</span>
prompts = [
<span class="hljs-string">f"Write a story about <span class="hljs-subst">{random.choice(themes)}</span> using <span class="hljs-subst">{structure}</span>."</span>,
<span class="hljs-string">f"Describe a character who embodies the concept of <span class="hljs-subst">{random.choice(themes)}</span>."</span>,
<span class="hljs-string">f"Create a dialogue that explores the theme of <span class="hljs-subst">{random.choice(themes)}</span>."</span>,
<span class="hljs-string">f"Write a setting description that incorporates <span class="hljs-subst">{<span class="hljs-string">', '</span>.join(themes[:<span class="hljs-number">3</span>])}</span>."</span>,
<span class="hljs-string">f"Craft a plot twist involving <span class="hljs-subst">{random.choice(themes)}</span> and <span class="hljs-subst">{random.choice(themes)}</span>."</span>
]
<span class="hljs-keyword">return</span> random.choice(prompts)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>():
quotes = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter your favorite book quotes (separated by semicolons): "</span>).split(<span class="hljs-string">';'</span>)
word_freq = analyze_quotes(quotes)
style = analyze_style(quotes)
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">5</span>):
prompt = generate_prompt(word_freq, style)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"\nGenerated prompt:"</span>)
<span class="hljs-built_in">print</span>(prompt)
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
main()
</code></pre>
Snippet:
<pre class="hljs language-javascript"><code class="hljs language-javascript"><span class="hljs-keyword">const</span> natural = <span class="hljs-built_in">require</span>(<span class="hljs-string">'natural'</span>);
<span class="hljs-keyword">const</span> tokenizer = <span class="hljs-keyword">new</span> natural.<span class="hljs-title class_">WordTokenizer</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title class_">TfIdf</span> = natural.<span class="hljs-property">TfIdf</span>;
<span class="hljs-keyword">const</span> tfidf = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TfIdf</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">analyzeQuotes</span>(<span class="hljs-params">quotes</span>) {
<span class="hljs-keyword">let</span> allWords = [];
quotes.<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">quote</span> =></span> {
<span class="hljs-keyword">const</span> words = tokenizer.<span class="hljs-title function_">tokenize</span>(quote.<span class="hljs-title function_">toLowerCase</span>());
allWords = allWords.<span class="hljs-title function_">concat</span>(words);
tfidf.<span class="hljs-title function_">addDocument</span>(words);
});
<span class="hljs-keyword">const</span> uniqueWords = [...<span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>(allWords)];
<span class="hljs-keyword">const</span> keyWords = uniqueWords
.<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">word</span> =></span> ({ word, <span class="hljs-attr">score</span>: tfidf.<span class="hljs-title function_">tfidf</span>(word, <span class="hljs-number">0</span>) }))
.<span class="hljs-title function_">sort</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> b.<span class="hljs-property">score</span> - a.<span class="hljs-property">score</span>)
.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>)
.<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.<span class="hljs-property">word</span>);
<span class="hljs-keyword">return</span> keyWords;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">analyzeWritingStyle</span>(<span class="hljs-params">quotes</span>) {
<span class="hljs-keyword">const</span> sentenceLengths = quotes.<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">quote</span> =></span> quote.<span class="hljs-title function_">split</span>(<span class="hljs-string">'.'</span>).<span class="hljs-property">length</span>);
<span class="hljs-keyword">const</span> avgSentenceLength = sentenceLengths.<span class="hljs-title function_">reduce</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> a + b) / sentenceLengths.<span class="hljs-property">length</span>;
<span class="hljs-keyword">const</span> wordLengths = quotes.<span class="hljs-title function_">flatMap</span>(<span class="hljs-function"><span class="hljs-params">quote</span> =></span> tokenizer.<span class="hljs-title function_">tokenize</span>(quote).<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">word</span> =></span> word.<span class="hljs-property">length</span>));
<span class="hljs-keyword">const</span> avgWordLength = wordLengths.<span class="hljs-title function_">reduce</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> a + b) / wordLengths.<span class="hljs-property">length</span>;
<span class="hljs-keyword">return</span> { avgSentenceLength, avgWordLength };
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">generatePrompts</span>(<span class="hljs-params">keyWords, style</span>) {
<span class="hljs-keyword">const</span> prompts = [
<span class="hljs-string">`Write a story that incorporates the words <span class="hljs-subst">${keyWords.slice(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>).join(<span class="hljs-string">', '</span>)}</span> and has an average sentence length of <span class="hljs-subst">${<span class="hljs-built_in">Math</span>.round(style.avgSentenceLength)}</span> sentences.`</span>,
<span class="hljs-string">`Create a character whose defining traits are related to <span class="hljs-subst">${keyWords.slice(<span class="hljs-number">3</span>, <span class="hljs-number">6</span>).join(<span class="hljs-string">', '</span>)}</span>. Use words with an average length of <span class="hljs-subst">${style.avgWordLength.toFixed(<span class="hljs-number">1</span>)}</span> characters.`</span>,
<span class="hljs-string">`Describe a setting inspired by <span class="hljs-subst">${keyWords.slice(<span class="hljs-number">6</span>, <span class="hljs-number">9</span>).join(<span class="hljs-string">', '</span>)}</span>. Maintain a rhythm similar to your favorite quotes.`</span>,
<span class="hljs-string">`Write a dialogue between two characters discussing <span class="hljs-subst">${keyWords[<span class="hljs-number">9</span>]}</span>. Mimic your preferred sentence structure and word choice.`</span>
];
<span class="hljs-keyword">return</span> prompts;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">generatePersonalizedPrompts</span>(<span class="hljs-params">quotes</span>) {
<span class="hljs-keyword">const</span> keyWords = <span class="hljs-title function_">analyzeQuotes</span>(quotes);
<span class="hljs-keyword">const</span> style = <span class="hljs-title function_">analyzeWritingStyle</span>(quotes);
<span class="hljs-keyword">return</span> <span class="hljs-title function_">generatePrompts</span>(keyWords, style);
}
<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> favoriteQuotes = [
<span class="hljs-string">"It was the best of times, it was the worst of times."</span>,
<span class="hljs-string">"To be or not to be, that is the question."</span>,
<span class="hljs-string">"All happy families are alike; each unhappy family is unhappy in its own way."</span>
];
<span class="hljs-keyword">const</span> personalizedPrompts = <span class="hljs-title function_">generatePersonalizedPrompts</span>(favoriteQuotes);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(personalizedPrompts);
</code></pre>
Snippet:
<pre class="hljs language-go"><code class="hljs language-go"><span class="hljs-keyword">package</span> main
<span class="hljs-keyword">import</span> (
<span class="hljs-string">"fmt"</span>
<span class="hljs-string">"math/rand"</span>
<span class="hljs-string">"strings"</span>
<span class="hljs-string">"time"</span>
<span class="hljs-string">"github.com/jdkato/prose/v2"</span>
)
<span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
Name <span class="hljs-type">string</span>
FavoriteQuotes []<span class="hljs-type">string</span>
WritingSamples []<span class="hljs-type">string</span>
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">analyzeWritingStyle</span><span class="hljs-params">(samples []<span class="hljs-type">string</span>)</span></span> <span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]<span class="hljs-type">float64</span> {
style := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]<span class="hljs-type">float64</span>)
totalWords := <span class="hljs-number">0</span>
totalSentences := <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> _, sample := <span class="hljs-keyword">range</span> samples {
doc, _ := prose.NewDocument(sample)
words := doc.Tokens()
sentences := doc.Sentences()
totalWords += <span class="hljs-built_in">len</span>(words)
totalSentences += <span class="hljs-built_in">len</span>(sentences)
<span class="hljs-keyword">for</span> _, word := <span class="hljs-keyword">range</span> words {
<span class="hljs-keyword">if</span> word.Tag == <span class="hljs-string">"JJ"</span> || word.Tag == <span class="hljs-string">"JJR"</span> || word.Tag == <span class="hljs-string">"JJS"</span> {
style[<span class="hljs-string">"adjectives"</span>]++
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> word.Tag == <span class="hljs-string">"RB"</span> || word.Tag == <span class="hljs-string">"RBR"</span> || word.Tag == <span class="hljs-string">"RBS"</span> {
style[<span class="hljs-string">"adverbs"</span>]++
}
}
}
style[<span class="hljs-string">"avgSentenceLength"</span>] = <span class="hljs-type">float64</span>(totalWords) / <span class="hljs-type">float64</span>(totalSentences)
style[<span class="hljs-string">"adjectives"</span>] /= <span class="hljs-type">float64</span>(totalWords)
style[<span class="hljs-string">"adverbs"</span>] /= <span class="hljs-type">float64</span>(totalWords)
<span class="hljs-keyword">return</span> style
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">generatePrompt</span><span class="hljs-params">(user User, style <span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]<span class="hljs-type">float64</span>)</span></span> <span class="hljs-type">string</span> {
themes := extractThemes(user.FavoriteQuotes)
prompt := <span class="hljs-string">""</span>
<span class="hljs-keyword">if</span> style[<span class="hljs-string">"avgSentenceLength"</span>] > <span class="hljs-number">15</span> {
prompt += <span class="hljs-string">"In a world where "</span>
} <span class="hljs-keyword">else</span> {
prompt += <span class="hljs-string">"Imagine: "</span>
}
prompt += themes[rand.Intn(<span class="hljs-built_in">len</span>(themes))] + <span class="hljs-string">", "</span>
<span class="hljs-keyword">if</span> style[<span class="hljs-string">"adjectives"</span>] > <span class="hljs-number">0.1</span> {
prompt += <span class="hljs-string">"a "</span> + getRandomAdjective() + <span class="hljs-string">" "</span>
}
prompt += getRandomNoun() + <span class="hljs-string">" must "</span>
<span class="hljs-keyword">if</span> style[<span class="hljs-string">"adverbs"</span>] > <span class="hljs-number">0.05</span> {
prompt += getRandomAdverb() + <span class="hljs-string">" "</span>
}
prompt += getRandomVerb() + <span class="hljs-string">"."</span>
<span class="hljs-keyword">return</span> prompt
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">extractThemes</span><span class="hljs-params">(quotes []<span class="hljs-type">string</span>)</span></span> []<span class="hljs-type">string</span> {
<span class="hljs-comment">// Implement theme extraction logic here</span>
<span class="hljs-keyword">return</span> []<span class="hljs-type">string</span>{<span class="hljs-string">"love"</span>, <span class="hljs-string">"betrayal"</span>, <span class="hljs-string">"redemption"</span>, <span class="hljs-string">"adventure"</span>}
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getRandomAdjective</span><span class="hljs-params">()</span></span> <span class="hljs-type">string</span> {
adjectives := []<span class="hljs-type">string</span>{<span class="hljs-string">"mysterious"</span>, <span class="hljs-string">"enchanted"</span>, <span class="hljs-string">"treacherous"</span>, <span class="hljs-string">"enigmatic"</span>}
<span class="hljs-keyword">return</span> adjectives[rand.Intn(<span class="hljs-built_in">len</span>(adjectives))]
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getRandomNoun</span><span class="hljs-params">()</span></span> <span class="hljs-type">string</span> {
nouns := []<span class="hljs-type">string</span>{<span class="hljs-string">"hero"</span>, <span class="hljs-string">"artifact"</span>, <span class="hljs-string">"kingdom"</span>, <span class="hljs-string">"secret"</span>}
<span class="hljs-keyword">return</span> nouns[rand.Intn(<span class="hljs-built_in">len</span>(nouns))]
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getRandomAdverb</span><span class="hljs-params">()</span></span> <span class="hljs-type">string</span> {
adverbs := []<span class="hljs-type">string</span>{<span class="hljs-string">"bravely"</span>, <span class="hljs-string">"cunningly"</span>, <span class="hljs-string">"desperately"</span>, <span class="hljs-string">"magically"</span>}
<span class="hljs-keyword">return</span> adverbs[rand.Intn(<span class="hljs-built_in">len</span>(adverbs))]
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getRandomVerb</span><span class="hljs-params">()</span></span> <span class="hljs-type">string</span> {
verbs := []<span class="hljs-type">string</span>{<span class="hljs-string">"overcome"</span>, <span class="hljs-string">"discover"</span>, <span class="hljs-string">"protect"</span>, <span class="hljs-string">"transform"</span>}
<span class="hljs-keyword">return</span> verbs[rand.Intn(<span class="hljs-built_in">len</span>(verbs))]
}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
rand.Seed(time.Now().UnixNano())
user := User{
Name: <span class="hljs-string">"Alice"</span>,
FavoriteQuotes: []<span class="hljs-type">string</span>{
<span class="hljs-string">"It was the best of times, it was the worst of times."</span>,
<span class="hljs-string">"To be or not to be, that is the question."</span>,
},
WritingSamples: []<span class="hljs-type">string</span>{
<span class="hljs-string">"The sun set behind the mountains, casting long shadows across the valley."</span>,
<span class="hljs-string">"She hesitated for a moment before opening the mysterious letter."</span>,
},
}
style := analyzeWritingStyle(user.WritingSamples)
prompt := generatePrompt(user, style)
fmt.Printf(<span class="hljs-string">"Generated prompt for %s:\n%s\n"</span>, user.Name, prompt)
}
</code></pre>