在字典上循环的问题

2024-09-22 10:13:45 发布

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

所以我这里有这个代码,但是当我到达最后一个for循环时,它只返回一个单词,而不是字典其余部分的x和*。感谢您的帮助

def main():
    print(parse_string("I had a good dog not a cat. A dog eats pizzas. A dog is happy. There is a happy dog there in the dog park."))
def parse_string(string):
    dicto = {}
    ast = ['*']
    x = ['X']
    boring = ['to', 'the', 'and', 'i', 'of', 'he', 'she',
            'a', "ill", "ive", 'but', 'by', 'we', 'whose'
            , 'how', 'go', 'such', 'this', 'me', 'can', "shes", "hes"
            , 'have', 'has', 'had', 'an', 'did', 'so', 'to', "well", 'on'
            , 'him', 'well', 'or', 'be', 'as', 'those', 'there', 'are', 'do'
            , 'too', 'if', 'it', 'at', 'what', 'you', 'will', 'in', 'with'
            , 'not', 'for', 'is', 'my', 'o', 'her', 'his', 'am']
    newstring = string.lower()
    newstring = newstring.replace('.', '')
    newstring = newstring.replace("'", '')
    finalstring = newstring.split()
    for word in finalstring:
        if word not in boring:
            if word not in dicto:
                dicto[word] = 1
            else:
                dicto[word] += 1
    for wrd in dicto:
        xmult = dicto[wrd] // 5
        astmult = dicto[wrd] % 5
        if xmult >= 1:
            return wrd + " " + xmult*x[0] + " " + astmult*ast[0]
        else:
            return wrd + " " + astmult*ast[0]

if __name__ == '__main__':
    main()

Tags: inforstringifismainnotast
1条回答
网友
1楼 · 发布于 2024-09-22 10:13:45

当您在字典中循环时,您正在循环中调用return。一旦满足其中一个条件,函数就返回,而不是完成循环的其余部分。我对你最后几行做了一些修改:

return_string = ""
for wrd in dicto:
    xmult = dicto[wrd] // 5
    astmult = dicto[wrd] % 5
    if xmult >= 1:
        return_string += wrd + " " + xmult*x[0] + " " + astmult*ast[0] + '\n'
    else:
        return_string += wrd + " " + astmult*ast[0] + '\n'
return return_string

相关问题 更多 >