문제

저는 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 여기서 할 것.해당 모듈은 컬렉션이 인쇄되는 방식을 사용자 정의하는 것(하위 객체 들여쓰기, 사전 키 또는 설정 요소가 표시되는 순서 제어 등)에 관한 것입니다.컬렉션을 전혀 인쇄하려는 것이 아니라 컬렉션에 대한 일부 정보만 인쇄하려는 것입니다.

가장 먼저 하고 싶은 일은 각 print 문에 대해 다시 작성하는 대신 컬렉션을 유지하는 것입니다.

counter = collections.Counter(stringToData)

다음으로 원하는 데이터를 가져오는 방법을 알아내야 합니다.한 쌍의 값을 찾는 방법은 이미 알고 있습니다.

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