programing

목록에서 단어 빈도를 세고 빈도별로 정렬

starjava 2023. 6. 6. 00:23
반응형

목록에서 단어 빈도를 세고 빈도별로 정렬

파이썬 3.3을 사용하고 있습니다.

저는 두 개의 목록을 만들어야 합니다. 하나는 고유한 단어이고 다른 하나는 단어의 빈도입니다.

빈도수가 가장 높은 단어가 목록에서 먼저 나오도록 빈도수 목록을 기준으로 고유 단어 목록을 정렬해야 합니다.

나는 디자인을 텍스트로 가지고 있지만 Python에서 어떻게 구현해야 할지 잘 모르겠습니다.

지금까지 찾은 방법은 다음 중 하나를 사용합니다.Counter또는 우리가 배우지 않은 사전.나는 이미 모든 단어가 포함된 파일에서 목록을 만들었지만 목록에서 각 단어의 빈도를 찾는 방법을 모릅니다.나는 이것을 하기 위해 루프가 필요하다는 것을 알지만 그것을 이해할 수 없습니다.

기본 설계는 다음과 같습니다.

 original list = ["the", "car",....]
 newlst = []
 frequency = []
 for word in the original list
       if word not in newlst:
           newlst.append(word)
           set frequency = 1
       else
           increase the frequency
 sort newlst based on frequency list 

이것을 사용합니다.

from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})

사용할 수 있습니다.

from collections import Counter

Python 2.7을 지원합니다. 자세한 내용은 여기를 참조하십시오.

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

딕트를 사용합니다.

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

하지만 당신은 먼저 파일을 읽고 dict로 변환해야 합니다.

파이썬 문서 예제, 사용자 및 카운터입니다.

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
words = file("test.txt", "r").read().split() #read the words into a list.
uniqWords = sorted(set(words)) #remove duplicate words and sort
for word in uniqWords:
    print words.count(word), word

판다들은 대답합니다:

import pandas as pd
original_list = ["the", "car", "is", "red", "red", "red", "yes", "it", "is", "is", "is"]
pd.Series(original_list).value_counts()

대신 오름차순으로 정렬하려면 다음과 같이 간단합니다.

pd.Series(original_list).value_counts().sort_values(ascending=True)

컬렉션을 사용하지 않고 다른 알고리즘을 사용하는 또 다른 솔루션:

def countWords(A):
   dic={}
   for x in A:
       if not x in  dic:        #Python 2.7: if not dic.has_key(x):
          dic[x] = A.count(x)
   return dic

dic = countWords(['apple','egg','apple','banana','egg','apple'])
sorted_items=sorted(dic.items())   # if you want it sorted

한 가지 방법은 목록 목록을 만들고 새 목록의 각 하위 목록에 단어와 카운트를 포함하는 것입니다.

list1 = []    #this is your original list of words
list2 = []    #this is a new list

for word in list1:
    if word in list2:
        list2.index(word)[1] += 1
    else:
        list2.append([word,0])

또는 보다 효율적으로:

for word in list1:
    try:
        list2.index(word)[1] += 1
    except:
        list2.append([word,0])

이것은 사전을 사용하는 것보다 덜 효율적이지만 더 기본적인 개념을 사용합니다.

reduct() - 기능적인 방법을 사용할 수 있습니다.

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}

카운터를 사용하는 것이 가장 좋은 방법일 수도 있지만, 그렇게 하지 않으려면 직접 이러한 방법으로 구현할 수도 있습니다.

# The list you already have
word_list = ['words', ..., 'other', 'words']
# Get a set of unique words from the list
word_set = set(word_list)
# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
    freq[word] = word_list.count(word) / float(len(word_list))

freq는 당신이 이미 가지고 있는 목록의 각 단어의 빈도로 끝날 것입니다.

필요합니다float정수 중 하나를 플로트로 변환하여 결과 값이 플로트가 되도록 합니다.

편집:

딕터 세트를 사용할 수 없는 경우 효율성이 떨어지는 다른 방법이 있습니다.

# The list you already have
word_list = ['words', ..., 'other', 'words']
unique_words = []
for word in word_list:
    if word not in unique_words:
        unique_words += [word]
word_frequencies = []
for word in unique_words:
    word_frequencies += [float(word_list.count(word)) / len(word_list)]
for i in range(len(unique_words)):
    print(unique_words[i] + ": " + word_frequencies[i])

의 지표.unique_words그리고.word_frequencies일치합니다.

이상적인 방법은 단어를 개수에 매핑하는 사전을 사용하는 것입니다.그러나 사용할 수 없는 경우 두 개의 목록(하나는 단어를 저장하고 다른 하나는 단어 수를 저장)을 사용할 수 있습니다.여기서는 단어와 숫자의 순서가 중요합니다.이를 구현하는 것은 어렵고 효율적이지 않습니다.

사용해 보십시오.

words = []
freqs = []

for line in sorted(original list): #takes all the lines in a text and sorts them
    line = line.rstrip() #strips them of their spaces
    if line not in words: #checks to see if line is in words
        words.append(line) #if not it adds it to the end words
        freqs.append(1) #and adds 1 to the end of freqs
    else:
        index = words.index(line) #if it is it will find where in words
        freqs[index] += 1 #and use the to change add 1 to the matching index in freqs

여기 코드 지원이 있습니다. 질문 is_char()는 해당 문자열만 유효한지 확인하십시오. 해시맵은 파이썬 사전입니다.

def is_word(word):
   cnt =0
   for c in word:

      if 'a' <= c <='z' or 'A' <= c <= 'Z' or '0' <= c <= '9' or c == '$':
          cnt +=1
   if cnt==len(word):
      return True
  return False

def words_freq(s):
  d={}
  for i in s.split():
    if is_word(i):
        if i in d:
            d[i] +=1
        else:
            d[i] = 1
   return d

 print(words_freq('the the sky$ is blue not green'))
for word in original_list:
   words_dict[word] = words_dict.get(word,0) + 1

sorted_dt = {key: value for key, value in sorted(words_dict.items(), key=lambda item: item[1], reverse=True)}

keys = list(sorted_dt.keys())
values = list(sorted_dt.values())
print(keys)
print(values)

간단한 방법

d = {}
l = ['Hi','Hello','Hey','Hello']
for a in l:
    d[a] = l.count(a)
print(d)
Output : {'Hi': 1, 'Hello': 2, 'Hey': 1} 

필요한 경우 단어와 빈도

def counter_(input_list_):
  lu = []
  for v in input_list_:
    ele = (v, lc.count(v)/len(lc)) #if you don't % remove <</len(lc)>>
    if ele not in lu:
      lu.append(ele)
  return lu

counter_(['a', 'n', 'f', 'a'])

출력:

[('a', 0.5), ('n', 0.25), ('f', 0.25)]

최선의 방법은 다음과 같습니다.

def wordListToFreqDict(wordlist):
    wordfreq = [wordlist.count(p) for p in wordlist]
    return dict(zip(wordlist, wordfreq))

다음을 시도합니다.wordListToFreqDict(originallist)

언급URL : https://stackoverflow.com/questions/20510768/count-frequency-of-words-in-a-list-and-sort-by-frequency

반응형