2012-10-20 3 views
5

나는 아래 스크립트를 수정하여 스크립트에 의해 생성 된 문장의 난수 중에서 단락을 생성하고자합니다. 즉, 개행을 추가하기 전에 문장의 난수 (1-5와 같은)를 연결하십시오.마크로프 체인 출력에서 ​​단락을 만드는 방법은 무엇입니까?

스크립트는 그대로 작동하지만 출력은 줄 바꿈으로 구분 된 짧은 문장입니다. 저는 단락으로 몇 문장을 모으고 싶습니다.

모범 사례에 대한 아이디어가 있으십니까? 감사.

""" 
    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 

편집 01 :

좋아, 내가 함께 단락에 문장을 수집하기 위해 잘 작동하는 간단한 "단락 래퍼,"자갈길했지만 그것은의 출력과 엉망 문장 생성기 - 예를 들어, 다른 문제들 중에서 첫 단어의 과도한 반복성을 얻고 있습니다.

그러나 전제는 소리입니다. 문장 루프의 기능이 단락 루프의 추가로 인해 왜 영향을 받았는지 알아 내야합니다. 당신이 문제를 볼 수 있는지 알려주십시오 :

### 
# 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 

편집 02 :

추가 sentence = [] 대답에 따라 아래 elif 문에. 기지로;

 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 

편집 03 :

이이 스크립트의 마지막 반복이다. 이 문제를 해결하는 데 도움을 주셔서 감사합니다. 나는 다른 사람들이 이것에 약간의 재미를 가질 수 있기를 바랄 뿐이다. ;)

FYI : 작은 아티팩트가 하나 있습니다.이 스크립트를 사용하면 정리할 수있는 여분의 단락 끝 부분 공간이 있습니다. 그러나, 그것 이외의, 마코프 체인 텍스트 생성의 완벽한 구현.

### 
# 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 

답변

3

당신은

elif newword in stopsentence: 

절에 돌아 가기

sentence = [] 

을 복사해야합니다.

그래서 편집

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 

는 외부 루프를 사용하지 않고 해결된다.

""" 
    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

죄송합니다. 네, 어느 시점에서 그걸 꺼내고 다시 넣는 것을 잊어 버렸을 것입니다. 통찰력을 가져 주셔서 감사합니다! 그 트릭을 거의했다. 문장 루프가 각 문장마다 동일한 시작 단어를 다시 사용하는 것처럼 보입니다. 문장 생성을 위해 선택한 첫 번째 단어를 혼합하는 방법에 대한 아이디어가 있습니까? –

+0

외부 루프가 필요없는 별도의 솔루션을 추가했습니다. – grieve

+0

현재 Python 3이 설치되어 있지 않으므로 구문에 대해 두 번째 해결 방법을 조정해야 할 수도 있습니다. – grieve

1

이 코드를 이해합니까? 나는 당신이 문장을 인쇄하고있는 비트를 찾을 수 있고, 반환하지 않고 여러 문장을 함께 인쇄하도록 바꿀 것입니다. 문장을 둘러싼 또 다른 반복문을 추가하여 여러 단락을 얻을 수 있습니다.

구문 힌트 :

print 'hello' 
print 'there' 
hello 
there 

print 'hello', 
print 'there' 
hello there 

print 'hello', 
print 
print 'there' 

점은 인쇄 문장의 끝에 쉼표가 줄 끝에 반환을 방지하고, 빈 인쇄 문이 수익을 출력한다는 것입니다.

+0

그래, 따라합니다. 문제는 'print'문으로 시도한 모든 것이 단락으로 문장을 모으는 데 도움이되지 않는다는 것입니다. 단 한 개의 거대한 단락을 만들 때 _all_ 줄 바꿈을 사용하지 않으면됩니다. 'while' 루프는 내가 생각하고 있던 것이지만, 문장 부분을 어떻게 감쌀 것인지는 잘 모르겠습니다. 내가 시도한 모든 것이 여러 가지 오류를 유발했기 때문에 전문가에게 물어 보았습니다. "x (1-5) 문장을 생성 한 다음 줄 바꿈을 넣은 다음"maxsentences "에 도달 할 때까지 반복하는 것이 가장 좋습니다. –

관련 문제