문제

단어 목록이 있다고 가정하고 해당 목록에 각 단어가 나타나는 횟수를 찾고 싶습니다.

이를 수행하는 명백한 방법은 다음과 같습니다.

words = "apple banana apple strawberry banana lemon"
uniques = set(words.split())
freqs = [(item, words.split().count(item)) for item in uniques]
print(freqs)

그러나 프로그램이 단어 목록을 두 번, 한 번 세트를 구축하고 두 번째로 외관 수를 계산하기 때문에이 코드가 좋지 않다는 것을 알게됩니다.

물론, 나는 목록을 통해 실행하고 계산을 할 수있는 함수를 쓸 수 있었지만 그렇게 피스닉은 아닙니다. 그렇다면 더 효율적이고 Pythonic 방법이 있습니까?

도움이 되었습니까?

해결책

DefaultDict 구조에!

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"

d = defaultdict(int)
for word in words.split():
    d[word] += 1

이것은 O (n)로 실행됩니다.

다른 팁

그만큼 Counter 수업 에서 collections 모듈은 이러한 유형의 문제를 해결하기 위해 구축 된 목적입니다.

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

표준 접근법 :

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"
words = words.split()
result = collections.defaultdict(int)
for word in words:
    result[word] += 1

print result

Groupby OneLiner :

from itertools import groupby

words = "apple banana apple strawberry banana lemon"
words = words.split()

result = dict((key, len(list(group))) for key, group in groupby(sorted(words)))
print result
freqs = {}
for word in words:
    freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize

나는 이것이 Triptych의 솔루션과 동일하지만 컬렉션을 가져 오지 않은다고 생각합니다. 또한 Selinap의 솔루션과 비슷하지만 더 읽기 쉬운 IMHO. Thomas Weigel의 솔루션과는 거의 동일하지만 예외는 사용하지 않습니다.

그러나 컬렉션 라이브러리에서 DefaultDict ()를 사용하는 것보다 느리게 될 수 있습니다. 값이 가져오고, 증가한 다음 다시 할당되므로. 단지 증가하는 대신. 그러나 += 사용은 내부적으로 동일 할 수 있습니다.

표준 사전 메소드를 사용하지 않으려면 (적절한 딕트 키를 증가시키는 목록을 통한 루프) :이를 시도 할 수 있습니다.

>>> from itertools import groupby
>>> myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon']
>>> [(k, len(list(g))) for k, g in groupby(sorted(myList))]
[('apple', 2), ('banana', 2), ('lemon', 1), ('strawberry', 1)]

O (n log n) 시간으로 실행됩니다.

DefaultDict없이 :

words = "apple banana apple strawberry banana lemon"
my_count = {}
for word in words.split():
    try: my_count[word] += 1
    except KeyError: my_count[word] = 1

그냥 count를 사용할 수 없습니까?

words = 'the quick brown fox jumps over the lazy gray dog'
words.count('z')
#output: 1

나는 약간의 스파크 운동을했다. 여기 내 해결책이있다.

tokens = ['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']

print {n: float(tokens.count(n))/float(len(tokens)) for n in tokens}

**#위의 출력 **

{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.16666666666666666}

Reduce ()를 사용하여 목록을 단일 딕으로 변환하십시오.

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})

보고

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
words = "apple banana apple strawberry banana lemon"
w=words.split()
e=list(set(w))       
for i in e:
   print(w.count(i))    #Prints frequency of every word in the list

도움이 되었기를 바랍니다!

아래 답변은 약간의 추가주기가 필요하지만 또 다른 방법입니다.

def func(tup):
    return tup[-1]


def print_words(filename):
    f = open("small.txt",'r')
    whole_content = (f.read()).lower()
    print whole_content
    list_content = whole_content.split()
    dict = {}
    for one_word in list_content:
        dict[one_word] = 0
    for one_word in list_content:
        dict[one_word] += 1
    print dict.items()
    print sorted(dict.items(),key=func)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top