簡體   English   中英

Function 接受字符串文本和正數 integer 並將其轉換為單詞列表

[英]Function that takes a string text and positive integer and converts it to list of words

卡在問題“寫一個 function repeat_word_count(text, n) ,它接受一個字符串文本和一個正 integer n,將文本轉換為基於簡單空格分隔的單詞列表(不刪除標點符號或更改大小寫),以及返回文本中出現 n 次或多次的單詞的排序列表。例如 repeat_word_count("wingswingswingswings", 2) -> output is ['wings'] 到目前為止我得到了:

def repeat_word_count(text, n):
    tally = {}
    for char in repeat_word_count:
        if char in tally:
            tally[char] += 1
        else:
            tally[char] = 1
        if tally[char] >= n :
            print(tally.sorted())

我想以'return tally'結束,但我不斷收到縮進錯誤。 但總的來說,我收到錯誤 TypeError: 'function' object is not iterable ,我不明白,如果有人也能解釋一下,那會很有幫助!

def repeat_word_count(text, n):
    #split string by " " into a list of words
    words = text.split(" ")

    words_iterator={}
    #interate throught the words
    for word in words:
        #if word is in the keys add 1 to his count 
        if word in words_iterator.keys():
            words_iterator[word]+=1
        #else add the word as a key and the counter as 1 giving is 
        #the first time the word appeard in the list
        else:
            words_iterator[word] = 1

    output=[]
    #parse the dict key by key 
    for key in words_iterator:
        # if the value of the key is bigger than n add key to list 
        if words_iterator[key]>=n:
            output.append(key)

    return output

這應該工作

Output 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM