Python函数只返回一个值

2024-10-02 12:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从函数返回从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 
>>> 

Tags: the函数inforlenreturnrangerandom
2条回答

它只返回一个单词,因为您的return语句在for循环中。它将经历第一次迭代,随机选择一个word并立即返回。在

这就是我要解决的方法-这也是random.choices的一个整洁的地方:

def generate(cfd, word = 'the', num = 5):
    arr = []                  
    for j in cfd[word]: # assuming your code to parse cfd is correct
        for k in range(cfd[word][j]):
            arr.append(j)
    return random.choices(arr, k=num)

您的return语句缩进太多。后退一级:

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)
        #print(word, end=' ')
        word = arr[int((len(arr))*random.random())] # choose the word randomly from the conditional distribution

    return(word)

当您注释掉return并改用print语句时,print将为for i in range(num)...中的每个迭代调用print。这就是为什么你得到5个打印输出。在

相关问题 更多 >

    热门问题