programing

목록에서 단어의 빈도를 계산하고 빈도별로 정렬

nasanasas 2020. 12. 6. 21:37
반응형

목록에서 단어의 빈도를 계산하고 빈도별로 정렬


Python 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)]

dict 사용

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

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

2. 파이썬 문서 예제입니다. re와 Counter를 사용하세요.

# 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

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}

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

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])

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


Counter를 사용하는 것이 가장 좋은 방법이지만 그렇게하고 싶지 않다면 직접 구현할 수 있습니다.

# 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정수 중 하나를 부동 소수점으로 변환 해야 하므로 결과 값은 부동 소수점이됩니다.

편집하다:

dict 또는 set을 사용할 수없는 경우 다른 덜 효율적인 방법이 있습니다.

# 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])

The indicies of unique_words and word_frequencies will match.


The ideal way is to use a dictionary that maps a word to it's count. But if you can't use that, you might want to use 2 lists - 1 storing the words, and the other one storing counts of words. Note that order of words and counts matters here. Implementing this would be hard and not very efficient.


Pandas answer:

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

If you wanted it in ascending order instead, it is as simple as:

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

Try this:

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

Here is code support your question is_char() check for validate string count those strings alone, Hashmap is dictionary in python

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'))

the best thing to do is :

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

then try to : wordListToFreqDict(originallist)

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

반응형