计算列表中单词的频率并按频率排序

2025-01-22 08:44:00
admin
原创
97
摘要:问题描述:我正在使用 Python 3.3我需要创建两个列表,一个用于唯一单词,另一个用于单词的频率。我必须根据频率列表对唯一单词列表进行排序,以便频率最高的单词位于列表的第一位。我有文本设计,但不确定如何用 Python 实现它。到目前为止,我发现的方法要么使用Counter我们尚未学习过的词典,要么使用词...

问题描述:

我正在使用 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 

解决方案 1:

使用这个

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

解决方案 2:

您可以使用

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

但是,您必须先读取文件,然后转换为字典。

  1. 这是 python 文档示例,使用 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)]

解决方案 3:

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

解决方案 4:

熊猫回答:

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)

解决方案 5:

还有一种不使用集合的算法的解决方案:

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

解决方案 6:

一种方法是制作一个列表列表,新列表中的每个子列表包含一个单词和一个计数:

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

这比使用字典效率较低,但它使用了更多基本概念。

解决方案 7:

您可以使用 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}

解决方案 8:

使用 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将其中一个整数转换为浮点数,因此结果值将是浮点数。

编辑:

如果你不能使用字典或者集合,这里还有另一种效率较低的方法:

# 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将匹配。

解决方案 9:

理想的方法是使用将单词映射到其计数的字典。但是如果你不能使用它,你可能需要使用 2 个列表 - 1 个存储单词,另一个存储单词计数。请注意,单词和计数的顺序在这里很重要。实现这一点会很困难,而且效率不高。

解决方案 10:

这里是支持你的问题的代码 is_char() 检查验证字符串单独计数这些字符串,Hashmap 是 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'))

解决方案 11:

简单的方法

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

解决方案 12:

尝试一下:

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

解决方案 13:

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)

解决方案 14:

如果需要的话

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

解决方案 15:

最好的办法是:

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

然后尝试:
wordListToFreqDict(originallist)

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1989  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1446  
  在当今快速发展的IT行业中,项目管理工具的选择对于项目的成功至关重要。随着技术的不断进步,项目经理们需要更加高效、灵活的工具来应对复杂的项目需求。本文将介绍2025年IT项目经理力推的10款管理工具,帮助您在项目管理中取得更好的成果。信创国产项目管理软件 - 禅道禅道是一款国产开源的项目管理软件,禅道开源版不限人数,功...
项目管理工具   0  
  在当今快速变化的商业环境中,项目管理软件已成为企业提升效率、优化资源分配和确保项目成功的关键工具。随着技术的不断进步,市场上涌现出众多功能各异的项目管理工具,每一款都有其独特的优势和适用场景。本文将深入评测2025年最受欢迎的10款项目管理软件,帮助您根据自身需求做出明智的选择。信创国产项目管理软件 - 禅道禅道是一款...
项目管理平台   2  
  产品开发效率对于企业的竞争力至关重要。在当今复杂多变的商业环境中,如何有效提升产品开发效率成为众多企业关注的焦点。产品生命周期管理(PLM)作为一种整合产品全生命周期信息的管理理念和技术,为提升产品开发效率提供了有力的支持。通过合理运用PLM,企业能够优化流程、加强协作、提高数据管理水平,从而实现产品开发的高效运作。接...
plm开发流程软件   3  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用