2017-12-06 2 views
-2

길이가 1 인 문자열에 대해 작동하는 함수를 작성했지만 더 긴 길이의 문자열에 대해서는 어떻게 작동하는지 잘 모릅니다. 문자열에서 파이썬의 부분 문자열 발생 백분율을 계산합니다.

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

세 단계 :

  • 분할 개별 단어로 입력; 파이썬의 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] 

다음은이 목록에있는 각 숫자의 수를 계산합니다. 움직일 수 있나요?

관련 문제