質問

私はPythonにかなり初めてですが、私が望むように持っているデータを表示するのに苦労しています。文字列で最も頻繁な文字を決定するこのコードがあります。しかし、私がそれをどのように印刷しているのかそのように: ('A', 3).

stringToData = raw_input("Please enter your string: ")
import collections
print (collections.Counter(stringToData).most_common(1)[0])

このコードをこれに似たものに操作する方法についての洞察を望んでいました。

print "In your string, there are: %s vowels and %s consonants." % (vowels, cons)

明らかに、「あなたの文字列では、最も頻繁なキャラクターは(文字)であり、それは(数)に発生しました」と言うでしょう。

私はPython 2.7を使用しています、そして私は pprint しかし、私はそれを既存のコードに組み込む方法を本当に理解していませんでした。

編集:基本的に、私が尋ねているのは、文字列で最も頻繁なキャラクターを見つけて「文字列で、最も頻繁なキャラクターは(数)(数)発生する(文字)(文字))などの方法で印刷する方法です。 「

役に立ちましたか?

解決

これがあなたが望むものであるかどうかはわかりませんが、これにより、最も頻繁なキャラクターが発生の数に続いて印刷されます。

import collections

char, num = collections.Counter(stringToData).most_common(1)[0]
print "In your string, the most frequent character is %s, which occurred %d times" % (char, num)

これは、最も頻繁なキャラクターと発生数のタプルを返します。

collections.Counter(stringToData).most_common(1)[0]
#output: for example: ('f', 5)

例:

stringToData = "aaa bbb ffffffff eeeee"
char, num = collections.Counter(stringToData).most_common(1)[0]
print "In your string, the most frequent character is %s, which occurred %d times" % (char, num)

出力は次のとおりです。

In your string, the most frequent character is f, which occurred 8 times

他のヒント

本当に何もありません pprint ここでやる。そのモジュールは、コレクションの印刷方法をカスタマイズすることです。サブオブジェクトを誘惑し、辞書キーやセット要素が表示される順序を制御します。コレクションをまったく印刷しようとはしていません。 。

最初にやりたいことは、印刷ステートメントごとにコレクションを再構築する代わりに、コレクションを維持することです。

counter = collections.Counter(stringToData)

次に、必要なデータを取得する方法を把握する必要があります。あなたはすでに1組の値を見つける方法を知っています:

letter, count = counter.most_common(1)[0]

あなたが尋ねた他のことは、母音と子音の数です。そのために、あなたはこのようなことをしたいと思うでしょう:

all_vowel = set('aeiouyAEIOUY')
all_consonants = set(string.ascii_letters) - all_vowels
vowels = sum(count for letter, count in counter.iteritems()
             if letter in all_vowels)
cons = sum(count for letter, count in counter.iteritems()
           if letter in all_consonants)

そして今、あなたは何らかの形式のフォーマットを使用してそれらを印刷する必要があります。

print "In your string, there are: %s vowels and %s consonants." % (vowels, cons)
print ("In your string, the most frequent character is %s, which occurred %s times."
       % (letter, count))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top