Domanda

Sto cercando la lavorazione di vari testi di regex e NLTK di pitone -che è a http: // www .nltk.org / libro- . Sto cercando di creare un generatore di testo casuale e sto avendo un piccolo problema. In primo luogo, ecco il mio flusso di codice:

  1. Inserisci una frase come -questo è chiamato stringa di ingresso trigger, viene assegnato a una variabile -

  2. Get più lunga parola nella stringa di innesco

  3. Cerca tutti i database di Project Gutenberg per le frasi che contengono questa parola -regardless di minuscole e maiuscole -

  4. Ritorna la frase più lunga che ha la parola ho parlato al punto 3

  5. Append la frase nella Fase 1 e Fase 4 insieme

  6. Assegna la frase nel passaggio 4 come la nuova frase 'trigger' e ripetere il processo. Si noti che ho per ottenere la parola più lunga nella seconda frase, e continuare così e così via -

Finora, sono stato in grado di farlo solo una volta. Quando provo a mantenere questo per continuare, il programma mantiene solo la stampa della prima frase i miei rendimenti di ricerca. Dovrebbe in realtà cercare la parola più lunga in questa nuova frase e mantenere l'applicazione il mio flusso di codice descritto in precedenza.

Di seguito è riportato il mio codice insieme a un campione di ingresso / uscita:

ingresso Esempio

  

"Thane di codice"

uscita Esempio

  

"Thane di codice Norvegia himselfe, con i numeri terribili, assistito da che la maggior parte disloyall Traytor, La Thane di Cawdor, ha cominciato un conflitto dismall, Fino a quel 's Bellona Bridegroome, LAPT in proofe, lo affrontò con Selfe - raffronti, Point contro Point, ribelle Arme 'contro Arme, Frenare il suo spirito lauish: e per concludere, La Victorie cadde su vs "

Ora, questo dovrebbe effettivamente prendere la frase che inizia con 'la Norvegia himselfe ....' e cercare la parola più lunga in esso e fare i passi sopra e così via, ma non è così. Eventuali suggerimenti? Grazie.

import nltk

from nltk.corpus import gutenberg

triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str

split_str = triggerSentence.split()#split the sentence into words

longestLength = 0

longestString = ""

montyPython = 1

while montyPython:

    #code to find the longest word in the trigger sentence input
    for piece in split_str:
        if len(piece) > longestLength:
            longestString = piece
            longestLength = len(piece)


    listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format-

    listOfWords = gutenberg.words()# all words in gutenberg books -list format-
    # I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence
    lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way. 

    longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len)
    #get longest sentence -list format with every word of sentence being an actual element-

    longestSent=[longestSentence]

    for word in longestSent:#convert the list longestSentence to an actual string
        sstr = " ".join(word)
    print triggerSentence + " "+ sstr
    triggerSentence = sstr
È stato utile?

Soluzione

Mr. La risposta di Hankin è più elegante, ma quanto segue è più in linea con l'approccio che si è iniziato con:

import sys
import string
import nltk
from nltk.corpus import gutenberg

def longest_element(p):
    """return the first element of p which has the greatest len()"""
    max_len = 0
    elem = None
    for e in p:
        if len(e) > max_len:
            elem = e
            max_len = len(e)
    return elem

def downcase(p):
    """returns a list of words in p shifted to lower case"""
    return map(string.lower, p)


def unique_words():
    """it turns out unique_words was never referenced so this is here
       for pedagogy"""
    # there are 2.6 million words in the gutenburg corpus but only ~42k unique
    # ignoring case, let's pare that down a bit
    for word in gutenberg.words():
        words.add(word.lower())
    print 'gutenberg.words() has', len(words), 'unique caseless words'
    return words

print 'loading gutenburg corpus...'
sentences = []
for sentence in gutenberg.sents():
    sentences.append(downcase(sentence))

trigger = sys.argv[1:]
target = longest_element(trigger).lower()
last_target = None

while target != last_target:
    matched_sentences = []
    for sentence in sentences:
        if target in sentence:
            matched_sentences.append(sentence)

    print '===', target, 'matched', len(matched_sentences), 'sentences'
    longestSentence = longest_element(matched_sentences)
    print ' '.join(longestSentence)

    trigger = longestSentence
    last_target = target
    target = longest_element(trigger).lower()

Data la tua frase di esempio, però, raggiunge fissazione in due cicli:

  

$ python nltkgut.py Thane di codice
  Caricamento Gutenburg corpus ...
  === bersaglio Thane abbinato 24 frasi
  norvegia himselfe, con terribile   numeri, assistiti da che la maggior parte   traytor disloyall, il signore di   Cawdor, ha iniziato un conflitto dismall,   fino bridegroome che Bellona 's,   LAPT in proofe, lo affrontò con   Selfe - confronti, contro il punto   punto, ribelle arme 'Contro arme   , Frenare il suo spirito lauish: e   In conclusione, la Victorie è caduta su vs
  === bersaglio bridegroome abbinato 1 frasi
  norvegia himselfe, con   numeri terribili, assistiti da quella   più traytor disloyall, il signore di   Cawdor, ha iniziato un conflitto dismall,   fino bridegroome che Bellona 's,   LAPT in proofe, lo affrontò con   Selfe - confronti, contro il punto   punto, ribelle arme 'Contro arme   , Frenare il suo spirito lauish: e   concludere, la Victorie è caduta su vs

Una parte della difficoltà con la risposta al l'ultimo problema è che ha fatto quello che hai chiesto, ma ha fatto una domanda più specifica di quanto si voleva una risposta. Così la risposta Got impantanati in alcune espressioni elenco piuttosto complicate che non sono sicuro di aver capito. Suggerisco che si fanno uso più liberale delle dichiarazioni di stampa e non il codice di importazione se non si sa cosa fa. Mentre scartare le espressioni della lista che ho trovato (come indicato), che non hai mai usato la lista di parole corpus. Le funzioni sono un aiuto anche.

Altri suggerimenti

Che ne dici di questo?

  1. Cerca parola più lunga d'innesco
  2. a trovare più lunga parola nella parola più lunga frase che contiene trovati in 1.
  3. La parola del 1. è la parola più lunga della frase di 2.

Che cosa succede? Suggerimento: la risposta inizia con "infinito". Per risolvere il problema si potrebbe trovare l'insieme di parole in minuscolo per essere utile.

A proposito, quando si pensa Monty Python diventa False e la finitura del programma?

Piuttosto che cercare l'intero corpus di volta in volta, può essere più veloce per costruire una mappa sola parola da alla frase più lunga che contiene quella parola. Ecco la mia (non verificato) il tentativo di fare questo.

import collections
from nltk.corpus import gutenberg

def words_in(sentence):
    """Generate all words in the sentence (lower-cased)"""
    for word in sentence.split():
        word = word.strip('.,"\'-:;')
        if word:
            yield word.lower()

def make_sentence_map(books):
    """Construct a map from words to the longest sentence containing the word."""
    result = collections.defaultdict(str)
    for book in books:
        for sentence in book:
            for word in words_in(sentence):
                if len(sentence) > len(result[word]):
                    result[word] = sent
    return result

def generate_random_text(sentence, sentence_map):
    while True:
        yield sentence
        longest_word = max(words_in(sentence), key=len)
        sentence = sentence_map[longest_word]

sentence_map = make_sentence_map(gutenberg.sents())
for sentence in generate_random_text('Thane of code.', sentence_map): 
    print sentence

Si sta assegnando all'esterno "split_str" del ciclo, quindi diventa il valore originale e poi la mantiene. È necessario assegnare all'inizio del ciclo while, in modo che cambia ogni volta.

import nltk

from nltk.corpus import gutenberg

triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str

longestLength = 0

longestString = ""

montyPython = 1

while montyPython:
    #so this is run every time through the loop
    split_str = triggerSentence.split()#split the sentence into words

    #code to find the longest word in the trigger sentence input
    for piece in split_str:
        if len(piece) > longestLength:
            longestString = piece
            longestLength = len(piece)


    listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format-

    listOfWords = gutenberg.words()# all words in gutenberg books -list format-
    # I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence
    lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way. 

    longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len)
    #get longest sentence -list format with every word of sentence being an actual element-

    longestSent=[longestSentence]

    for word in longestSent:#convert the list longestSentence to an actual string
        sstr = " ".join(word)
    print triggerSentence + " "+ sstr
    triggerSentence = sstr
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top