我想从函数返回从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
>>>
它只返回一个单词,因为您的
return
语句在for
循环中。它将经历第一次迭代,随机选择一个word
并立即返回。在这就是我要解决的方法-这也是
random.choices
的一个整洁的地方:您的
return
语句缩进太多。后退一级:当您注释掉
return
并改用print
语句时,print
将为for i in range(num)...
中的每个迭代调用print
。这就是为什么你得到5个打印输出。在相关问题 更多 >
编程相关推荐