2016-07-19 16 views
-4

与えられた文章で各文字数を取得したい。私は以下のコードを試して、すべての文字の数を取得したが、出力に繰り返しの文字数が表示されます。繰り返し文字を削除する方法。Python文字列の文字数をカウントする

def countwords(x): 
    x=x.lower() 
    for i in x: 
     print(i,'in',x.count(i)) 

x=str(input("Enter a paragraph ")) 
countwords(x) 

私の出力は、次のとおりです。

enter image description here

私の出力は何をする..カウントし、繰り返し文字にスペースを含めることはできません.... !!!

+1

スペースを確認して除外しますか?あなたがすでに数えたキャラクターを保存し、それらを繰り返さない?アルゴリズムを変更して、文字列を一度だけ繰り返します(ヒント: 'Counter')?本当にアイデアはありませんか? – jonrsharpe

+0

Pythonコードをポストするときに字下げを正しく転記するようにしてください。ひどくインデントされたPythonコードはナンセンスです。 – khelwood

答えて

1

チェックこのコード:

my_string = "count a character occurance" 
my_list = list(my_string) 
print (my_list) 
get_unique_char = set(my_list) 
print (get_unique_char) 

for key in get_unique_char: 
    print (key, my_string.count(key)) 
+0

中間の 'my_list'を作成する必要はありません(文字列は反復可能です)、そしてスペースはあなたの出力に含まれます。 – jedwards

0

dictを使用してください。

def countwords(x): 
    d = dict() 
    x=x.lower() 
    for i in x: 
     if i in d.keys(): 
      d[i] = d[i] +1; 
     else: 
      d[i] = 1; 

    for i in d.keys(): 
      print i + " " + d[i] 
+2

'dict.setdefault'や' defaultdict'や 'Counter'を使う方がずっと簡単になり、' if'と 'else'の条件を並べ替えるだけです。また、比較やループのために '.keys()'を指定する必要もありません。また、拡張割り当てを使用することもできます。基本的には正しい考えですが、実装がはるかに優れている可能性があります。 – jonrsharpe

+0

@jonrsharpe:初心者を理解させるためのより簡単な実装が良い方法だと感じました。 –

+2

怠惰なユーザに実装を投げ捨てるのではなく、何が起こっていたのかの説明があればそれかもしれません。 – jonrsharpe

1

いくつかの異なるアプローチ、最もjonrsharpeのコメントで、私はシンプルsetをお勧めしたいの示唆があります。いくつかの他の人と一緒に

セットアプローチは、以下が含まれる:Pythonの辞書は順不同であるため、文字の順序が異なっていてもよいが

# An approach using a set 
def countwords_set(s): 
    for c in set(s): 
     if c == ' ': continue 
     print(c, 'in', s.count(c)) 

# An approach using a standard dict 
def countwords_dict(s): 
    d = dict() 
    for c in s: 
     if c == ' ': continue    # Skip spaces 
     d[c] = d.get(c,0) + 1    # Use the .get method in case the 
              # key isn't set 

    for c,x in d.items():     # Display results 
     print(c, 'in', x) 


# An approach using a defaultdict (from the collections module) 
def countwords_ddict(s): 
    from collections import defaultdict  # Typically, imports go at the top 

    d = defaultdict(int) 

    for c in s: 
     if c == ' ': continue 
     d[c] += 1 

    for c,x in d.items(): 
     print(c, 'in', x) 


# An approach using a Counter (from the collections module) 
def countwords_counter(s): 
    from collections import Counter   # Typically, imports go at the top 

    counter = Counter(s) 

    # Counters can be accessed like dicts 
    for c,x in counter.items(): 
     if c == ' ': continue 
     print(c, 'in', x) 


# User input and comparison 
s = str(input("Enter a paragraph ")) 
s = s.lower() 

countwords_set(s) 
print("---") 

countwords_dict(s) 
print("---") 

countwords_ddict(s) 
print("---") 

countwords_counter(s) 
print("---") 

出力は、それぞれのアプローチのための本質的に同じです。

関連する問題