2016-11-16 20 views
1

私は初心者です。私は.txtファイルからリストを返すpythonプログラムを書こうとしています。さまざまな文字長の単語の数を示します。たとえば、「リスト内には、3文字以下の5語があります。リストの文字数をカウントするPython

def count_lengths(text): 

    up_to_three = 0 
    four_or_five = 0 
    six_to_nine = 0 
    ten_or_more = 0 
    newtext = text.split(' ') 

def main(): 

    filename = "gb.txt" 
    text = readfile(filename) 
    word_lengths = count_lengths(text) 
    print(word_lengths) 

リストに.txtファイルを変換した後、私はかなり迷ってしまいました。ここで

は、私がこれまで持っているものです。誰かがこれで私を助けることができますか?

答えて

0

おそらく最も簡単にはCounterを使用することであろう。

from collections import Counter 

text = 'Some text from your file that you have read into this variable' 

    print(sorted(map(len, text.split()))) 

    word_lengths = {} 

    # cumulate number of words 
    total = 0 
    for k,v in sorted(Counter(map(len, text.split())).items()): 
     total += v 
     word_lengths[k] = total 


    print(word_lengths) 
    # {8: 12, 3: 1, 4: 11} 
+0

あなたは最初にソートする必要があります。P –

+0

@JoranBeasleyありがとうございました。 Soring added – Marcin

0

collections.Counterを使用して各長さにおける単語の数としてワード長と値と鍵とdict様オブジェクトをもたらします。

>>> s = 'hello this is a sentence with words of varying lengths' 

まず、全てのワード長を追跡:

>>> from collections import Counter 
>>> word_lengths = Counter(lengths) 
>>> word_lengths 
Counter({2: 2, 4: 2, 5: 2, 7: 2, 1: 1, 8: 1}) 

編集:

>>> lengths = [len(word) for word in s.split()] 
>>> lengths 
[5, 4, 2, 1, 8, 4, 5, 2, 7, 7] 

その後、様々な長さで上記の文字列で発生するどのように多くの単語数えますので、累積合計が必要です。

def count_lengths(text, n): 
    lengths = [len(word) for word in text.split()] 
    word_lengths = Counter(lengths) 
    # count the total number of words with lengths less than or equal to n 
    n_and_less_chars = sum(value for key, value in word_lengths.items() if key <= n) 
    return n_and_less_chars 

はそれを試す:

>>> print(count_lengths(s, 5)) 
7 

を、我々は、上記の例の文字列を見ると、私たちは5文字以下で7つのワードは、実際には、そこにあることがわかります。

+0

OPsは累積合計を求めている、すなわち、長さ5以下の5単語がある。 – Marcin

関連する問題