2012-10-20 13 views
5

Vorrei modificare lo script qui sotto in modo da creare paragrafi da un numero casuale di frasi generate dallo script. In altre parole, concatena un numero casuale (come 1-5) di frasi prima di aggiungere una nuova riga.Come creare paragrafi dall'output della catena markov?

Lo script funziona bene così com'è, ma l'output è composto da brevi frasi separate da una nuova riga. Vorrei raccogliere alcune frasi in paragrafi.

Qualche idea sulle migliori pratiche? Grazie.

""" 
    from: http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/?in=lang-python 
""" 

import random; 
import sys; 

stopword = "\n" # Since we split on whitespace, this can never be a word 
stopsentence = (".", "!", "?",) # Cause a "new sentence" if found at the end of a word 
sentencesep = "\n" #String used to seperate sentences 


# GENERATE TABLE 
w1 = stopword 
w2 = stopword 
table = {} 

for line in sys.stdin: 
    for word in line.split(): 
     if word[-1] in stopsentence: 
      table.setdefault((w1, w2), []).append(word[0:-1]) 
      w1, w2 = w2, word[0:-1] 
      word = word[-1] 
     table.setdefault((w1, w2), []).append(word) 
     w1, w2 = w2, word 
# Mark the end of the file 
table.setdefault((w1, w2), []).append(stopword) 

# GENERATE SENTENCE OUTPUT 
maxsentences = 20 

w1 = stopword 
w2 = stopword 
sentencecount = 0 
sentence = [] 

while sentencecount < maxsentences: 
    newword = random.choice(table[(w1, w2)]) 
    if newword == stopword: sys.exit() 
    if newword in stopsentence: 
     print ("%s%s%s" % (" ".join(sentence), newword, sentencesep)) 
     sentence = [] 
     sentencecount += 1 
    else: 
     sentence.append(newword) 
    w1, w2 = w2, newword 

EDIT 01:

Va bene, ho messo insieme un semplice "paragrafo involucro", che funziona bene per raccogliere le frasi in paragrafi, ma pasticciato con l'uscita del generatore di frasi - Sto ricevendo un'eccessiva ripetitività delle prime parole, per esempio, tra le altre questioni.

Ma la premessa è valida; Ho solo bisogno di capire perché la funzionalità del ciclo della frase è stata influenzata dall'aggiunta del ciclo di paragrafo. Si prega di avvisare se si può vedere il problema:

### 
# usage: $ python markov_sentences.py <input.txt> output.txt 
# from: http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/?in=lang-python 
### 

import random; 
import sys; 

stopword = "\n" # Since we split on whitespace, this can never be a word 
stopsentence = (".", "!", "?",) # Cause a "new sentence" if found at the end of a word 
paragraphsep = "\n\n" #String used to seperate sentences 


# GENERATE TABLE 
w1 = stopword 
w2 = stopword 
table = {} 

for line in sys.stdin: 
    for word in line.split(): 
     if word[-1] in stopsentence: 
      table.setdefault((w1, w2), []).append(word[0:-1]) 
      w1, w2 = w2, word[0:-1] 
      word = word[-1] 
     table.setdefault((w1, w2), []).append(word) 
     w1, w2 = w2, word 
# Mark the end of the file 
table.setdefault((w1, w2), []).append(stopword) 

# GENERATE PARAGRAPH OUTPUT 
maxparagraphs = 10 
paragraphs = 0 # reset the outer 'while' loop counter to zero 

while paragraphs < maxparagraphs: # start outer loop, until maxparagraphs is reached 
    w1 = stopword 
    w2 = stopword 
    stopsentence = (".", "!", "?",) 
    sentence = [] 
    sentencecount = 0 # reset the inner 'while' loop counter to zero 
    maxsentences = random.randrange(1,5) # random sentences per paragraph 

    while sentencecount < maxsentences: # start inner loop, until maxsentences is reached 
     newword = random.choice(table[(w1, w2)]) # random word from word table 
     if newword == stopword: sys.exit() 
     elif newword in stopsentence: 
      print ("%s%s" % (" ".join(sentence), newword), end=" ") 
      sentencecount += 1 # increment the sentence counter 
     else: 
      sentence.append(newword) 
     w1, w2 = w2, newword 
    print (paragraphsep) # newline space 
    paragraphs = paragraphs + 1 # increment the paragraph counter 


# EOF 

EDIT 02:

Aggiunto sentence = [] come da risposta qui sotto in elif dichiarazione. A wit;

 elif newword in stopsentence: 
      print ("%s%s" % (" ".join(sentence), newword), end=" ") 
      sentence = [] # I have to be here to make the new sentence start as an empty list!!! 
      sentencecount += 1 # increment the sentence counter 

EDIT 03:

Questo è l'iterazione finale di questo script. Grazie a lamentarsi per l'aiuto nel sistemare questo fuori. Spero che gli altri possano divertirsi con questo, lo so lo farò. ;)

FYI: C'è un piccolo artefatto: c'è uno spazio extra di fine paragrafo che potresti voler pulire se usi questo script. Ma, a parte questo, una perfetta implementazione della generazione del testo della catena markov.

### 
# usage: python markov_sentences.py <input.txt> output.txt 
# from: http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/?in=lang-python 
### 

import random; 
import sys; 

stopword = "\n" # Since we split on whitespace, this can never be a word 
stopsentence = (".", "!", "?",) # Cause a "new sentence" if found at the end of a word 
sentencesep = "\n" #String used to seperate sentences 


# GENERATE TABLE 
w1 = stopword 
w2 = stopword 
table = {} 

for line in sys.stdin: 
    for word in line.split(): 
     if word[-1] in stopsentence: 
      table.setdefault((w1, w2), []).append(word[0:-1]) 
      w1, w2 = w2, word[0:-1] 
      word = word[-1] 
     table.setdefault((w1, w2), []).append(word) 
     w1, w2 = w2, word 
# Mark the end of the file 
table.setdefault((w1, w2), []).append(stopword) 

# GENERATE SENTENCE OUTPUT 
maxsentences = 20 

w1 = stopword 
w2 = stopword 
sentencecount = 0 
sentence = [] 
paragraphsep = "\n" 
count = random.randrange(1,5) 

while sentencecount < maxsentences: 
    newword = random.choice(table[(w1, w2)]) # random word from word table 
    if newword == stopword: sys.exit() 
    if newword in stopsentence: 
     print ("%s%s" % (" ".join(sentence), newword), end=" ") 
     sentence = [] 
     sentencecount += 1 # increment the sentence counter 
     count -= 1 
     if count == 0: 
      count = random.randrange(1,5) 
      print (paragraphsep) # newline space 
    else: 
     sentence.append(newword) 
    w1, w2 = w2, newword 


# EOF 

risposta

3

è necessario copiare

sentence = [] 

Torna nella clausola di

elif newword in stopsentence: 

.

Così

while paragraphs < maxparagraphs: # start outer loop, until maxparagraphs is reached 
    w1 = stopword 
    w2 = stopword 
    stopsentence = (".", "!", "?",) 
    sentence = [] 
    sentencecount = 0 # reset the inner 'while' loop counter to zero 
    maxsentences = random.randrange(1,5) # random sentences per paragraph 

    while sentencecount < maxsentences: # start inner loop, until maxsentences is reached 
     newword = random.choice(table[(w1, w2)]) # random word from word table 
     if newword == stopword: sys.exit() 
     elif newword in stopsentence: 
      print ("%s%s" % (" ".join(sentence), newword), end=" ") 
      sentence = [] # I have to be here to make the new sentence start as an empty list!!! 
      sentencecount += 1 # increment the sentence counter 
     else: 
      sentence.append(newword) 
     w1, w2 = w2, newword 
    print (paragraphsep) # newline space 
    paragraphs = paragraphs + 1 # increment the paragraph counter 

Modifica

Ecco una soluzione senza utilizzare il ciclo esterno.

""" 
    from: http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/?in=lang-python 
""" 

import random; 
import sys; 

stopword = "\n" # Since we split on whitespace, this can never be a word 
stopsentence = (".", "!", "?",) # Cause a "new sentence" if found at the end of a word 
sentencesep = "\n" #String used to seperate sentences 


# GENERATE TABLE 
w1 = stopword 
w2 = stopword 
table = {} 

for line in sys.stdin: 
    for word in line.split(): 
     if word[-1] in stopsentence: 
      table.setdefault((w1, w2), []).append(word[0:-1]) 
      w1, w2 = w2, word[0:-1] 
      word = word[-1] 
     table.setdefault((w1, w2), []).append(word) 
     w1, w2 = w2, word 
# Mark the end of the file 
table.setdefault((w1, w2), []).append(stopword) 

# GENERATE SENTENCE OUTPUT 
maxsentences = 20 

w1 = stopword 
w2 = stopword 
sentencecount = 0 
sentence = [] 
paragraphsep == "\n\n" 
count = random.randrange(1,5) 

while sentencecount < maxsentences: 
    newword = random.choice(table[(w1, w2)]) 
    if newword == stopword: sys.exit() 
    if newword in stopsentence: 
     print ("%s%s" % (" ".join(sentence), newword), end=" ") 
     sentence = [] 
     sentencecount += 1 
     count -= 1 
     if count == 0: 
      count = random.randrange(1,5) 
      print (paragraphsep) 
    else: 
     sentence.append(newword) 
    w1, w2 = w2, newword 
+0

Oops! Sì, devo averlo tirato fuori a un certo punto e ho dimenticato di rimetterlo. Grazie per l'intuizione! Questo ha fatto il trucco - quasi. Sembra che il ciclo della frase riutilizzi le stesse parole di partenza per ogni frase. Qualche idea su come mescolare le prime parole che sceglie per la generazione della frase? –

+0

Ho aggiunto una soluzione separata che non ha bisogno del ciclo esterno. – grieve

+0

Al momento non ho Python 3 installato, quindi potrebbe essere necessario modificare la seconda soluzione per la sintassi. – grieve

1

Hai capito questo codice? Scommetto che puoi trovare il bit che sta stampando la frase e cambiarla per stampare più frasi insieme, senza resi. È possibile aggiungere un altro ciclo mentre si circonda il bit di frasi per ottenere più paragrafi.

Sintassi suggerimento:

print 'hello' 
print 'there' 
hello 
there 

print 'hello', 
print 'there' 
hello there 

print 'hello', 
print 
print 'there' 

Il punto è che una virgola alla fine di una dichiarazione di stampa impedisce il ritorno alla fine della linea, e una dichiarazione di stampa in bianco stampa un ritorno.

+0

Sì, seguo. Il problema è che tutto ciò che ho provato con l'istruzione 'print' non ha aiutato a raggruppare le frasi in paragrafi (a meno che non contiate di eliminare tutte le interruzioni di riga, creando un paragrafo gigante). Il ciclo 'while' è quello che stavo pensando, ma non ero abbastanza sicuro di come avvolgere la parte della frase. Tutto ciò che ho provato ha portato a vari errori, quindi ho pensato di chiedere agli esperti. Qual è il modo migliore per dirlo "generare x (1-5 per esempio) quantità di frasi, quindi inserire un'interruzione di riga, e poi ripetere fino a raggiungere" maxsentences "? –

Problemi correlati