我想从函数返回从nltk。为什么此函数只返回一个单词,如果我对返回值进行注释并取消注释,则print将返回5个单词。在
我想返回它们,并在另一个函数中使用它们。在file = open('Text/Walden.txt', 'r',encoding="utf8")
walden = file.read()
walden = walden.split()
def makePairs(arr):
pairs = []
for i in range(len(arr)):
if i < len(arr)-1:
temp = (arr[i], arr[i+1])
pairs.append(temp)
return pairs
def generate(cfd, word = 'the', num = 5):
for i in range(num):
arr = [] # make an array with the words shown by proper count
for j in cfd[word]:
for k in range(cfd[word][j]):
arr.append(j)
word = arr[int((len(arr))*random.random())] # choose the word randomly from the conditional distribution
print(word, end=' ')
return(word)
#return random.choices(arr, k=num)
pairs = makePairs(walden)
cfd = nltk.ConditionalFreqDist(pairs)
generate(cfd)
现在的输出如下:
^{pr2}$
或者But girl?"— print girl?"—
cases
>>>