나는 아래 스크립트를 수정하여 스크립트에 의해 생성 된 문장의 난수 중에서 단락을 생성하고자합니다. 즉, 개행을 추가하기 전에 문장의 난수 (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
죄송합니다. 네, 어느 시점에서 그걸 꺼내고 다시 넣는 것을 잊어 버렸을 것입니다. 통찰력을 가져 주셔서 감사합니다! 그 트릭을 거의했다. 문장 루프가 각 문장마다 동일한 시작 단어를 다시 사용하는 것처럼 보입니다. 문장 생성을 위해 선택한 첫 번째 단어를 혼합하는 방법에 대한 아이디어가 있습니까? –
외부 루프가 필요없는 별도의 솔루션을 추가했습니다. – grieve
현재 Python 3이 설치되어 있지 않으므로 구문에 대해 두 번째 해결 방법을 조정해야 할 수도 있습니다. – grieve