2017-12-06 25 views
-2

長さ1の文字列で機能する関数を書いたが、長めの文字列では機能するようには考えていない。string、pythonの部分文字列出現率を計算する

def function(text, n): 
    dict={} 
    char_count=0 

    for c in text: 
     keys=dict.keys() 
     if c.isalpha()==True: 
      char_count+=1 
      if c in keys: 
       dict[c] +=1 
      else: 
       dict[c]=1 
    for key in dict: 
     dict[key]=dict[key]/char_count 

    return dict 

インポートの使用は非常に歓迎ではありません:/

+3

ヒント:最初に['str.split()'](https://docs.python.org/2/library/stdtypes.html#str.split)を使用して文字列を分割し、別のサイズの数を数えます結果リスト内の要素。 – zwer

+0

誰かがそれぞれ答えを落としているようです。説明してください? – Prune

答えて

-1

あなたは長さnの各部分の上に反復するよりも発電機を作成することができます。その後、カウントを追跡する辞書のキーとして使用します。

def substring_percentage(text, n): 
    out = {} 
    n_substrings = len(text)-n+1 
    subs = (text[i:i+n] for i in range(n_substrings)) 
    for s in subs: 
     if s in out: 
      out[s] += 100/n_substrings 
     else: 
      out[s] = 100/n_substrings 
    return out 

テスト:

s = 'I have an assignment to write a function that will receive a sentence and a number ' \ 
    +'and will return the percentage of the occurrences of strings of length of the given ' \ 
    +'number in the given string.' 

pcts = substring_percentage(s, 4) 
sorted(pcts.items(), key=lambda x: x[::-1], reverse=True) 
# returns: 
[('the ', 2.094240837696335), 
(' the', 2.094240837696335), 
(' of ', 2.094240837696335), 
('n th', 1.5706806282722514), 
... 
(' an ', 0.5235602094240838), 
(' a s', 0.5235602094240838), 
(' a n', 0.5235602094240838), 
(' a f', 0.5235602094240838)] 
+0

しかし、私はどのように関数をあなたのソリューションでスペースを数えないようにするのですか? – Elina

+0

「私は帽子です」 - >「iamahat」のようなスペースを削除する場合と同じですか? – James

+0

ありがとう!私はちょうどそれらのスペースを持っている部分文字列をカウントする機能を望んでいないので、私は辞書に追加する前に追加しました:) – Elina

-1

3つのステップ:

  • スプリット個々の単語に入力。 Pythonのsplit関数は素晴らしいリストを返します。
  • 対応する単語長のリストを作成します。各要素にlenを使用してください。
  • count関数を使用して、各長さのオカレンスを数えます。それらの結果を辞書に入れてください。例えば

、あなたが開始した場合:個々の単語に

sentence = "Now I will a rhyme construct "  + \ 
      "By chosen words the young instruct " + \ 
      "Cunningly ensured endeavour "  + \ 
      "Con it and remember ever "   + \ 
      "Widths of circle here you see "  + \ 
      "Stretchd out in strange obscurity " 

スプリットこれ。各単語の長さをリストします。

[3, 1, 4, 1, 5, 9, 2, 6, 
5, 3, 5, 8, 9, 7, 9, 3, 
2, 3, 8, 4, 6, 2, 6, 4, 
3, 3, 8, 3, 2, 7, 9] 

次に、このリストに含まれる各番号の数を数えます。 あなたは動いていますか?

関連する問題