所以我在这里有这个代码,但是当我到达最后一个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()
答案 0 :(得分:1)
当您循环浏览字典时,您正在循环中调用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