【问题标题】:How to use multiple counts to make a dictionary如何使用多个计数来制作字典
【发布时间】:2018-10-10 04:18:14
【问题描述】:

这是一个很难问的问题。但是,到目前为止我有这个代码:

#create the dictionary with the word profiles

        for u in unique:
            kw = u
            count_word = [i for i in temp for j in i.split() if j == kw]
            count_dict = {j: i.count(j) for i in count_word for j in i.split() if j != kw}
            print(kw)

            #format the dictionary
            for a, c in sorted(count_dict.items(), key=lambda x: x[0]):
                print('{}: {}'.format(a, c))
            print()

这正是我想要它做的,除了独特的词也需要一个计数器。在下面的示例中,我将 River 作为唯一词,它将遍历代码并与临时列表进行比较。其输出如下:

river (# This should be river: 4 not just river)
atlantic: 1
branch: 1
commonplace: 1
considering: 1
contrary: 1
country: 1
cover: 1
crookedest: 1
crow: 1
degrees: 1
delaware: 1
drainage-basin: 1
draws: 1
fly: 1
forty-five: 1
ground: 1
idaho: 1
journey: 1
longest: 1
longitude: 1
main: 1
miles: 1
missouri: 1
pacific: 1
part: 1
remarkable: 1
safe: 1
seaboard: 1
seems: 1
seventy-five: 1
six: 1
slope: 1
spread: 1
states: 1
supply: 1
territories: 1
twenty-eight: 1
uses: 1
vast: 1
water: 1
ways: 1
world: 1
world--four: 1

它看起来很棒,正是我想要做的。除了,看看列表顶部的河流没有计数吗? River 在文本中出现了 4 次,所以我想要一个计数器来计算河流 4 次,同时仍然给我下面的输出。

这些是我为此使用的列表(临时)和设置(唯一):

独特

{'longest', 'considering', 'receives', 'water', 'discharges', 'atlantic', 'austria', 'part', 'idaho', 'main', 'drainage-basin', 'st', 'twenty-five', 'seventy-five', 'slope--a', 'world--four', 'remarkable', 'rivers', 'country', 'crookedest', 'areas', 'ireland', 'fifty-four', 'portugal', 'valley', 'france', 'almost', 'branch', 'twenty-eight', 'fertile', 'england', 'crow', 'spread', 'italy', 'journey', 'germany', 'river', 'draws', 'exceptionally', 'scotland', 'fly', 'uses', 'supply', 'region', 'rhine', 'ground', 'thirty-eight', 'thames', 'pacific', 'degrees', 'mississippi', 'lawrence', 'six', 'cover', 'subordinate', 'flats', 'navigable', 'area', 'proper', 'states', 'safe', 'wide', 'territories', 'vast', 'hundreds', 'contrary', 'missouri', 'commonplace', 'gulf', 'worth', 'seaboard', 'steamboats', 'wales', 'turkey', 'combined', 'delaware', 'forty-five', 'carries', 'seems', 'reading', 'keels', 'longitude', 'spain', 'ways'}

温度

['mississippi worth reading about', ' commonplace river contrary ways remarkable', ' considering missouri main branch longest river world--four miles', ' seems safe crookedest river world part journey uses cover ground crow fly six seventy-five', ' discharges water st', ' lawrence twenty-five rhine thirty-eight thames', ' river vast drainage-basin draws water supply twenty-eight states territories delaware atlantic seaboard country idaho pacific slope spread forty-five degrees longitude', ' mississippi receives carries gulf water fifty-four subordinate rivers navigable steamboats hundreds navigable flats keels', ' area drainage-basin combined areas england wales scotland ireland france spain portugal germany austria italy turkey almost wide region fertile mississippi valley proper exceptionally so']

如果您有任何问题,请随时提出。

谢谢,

【问题讨论】:

  • 所以您只想计算字符串列表中的单词数?
  • 到目前为止,唯一列表中的每个元素都只被打印出来,我该如何计算,例如,如果河流是 kw,那么一旦它计数为 2 并最终达到 4,如解释以上。

标签: python python-3.x


【解决方案1】:
import collections

temp = ['mississippi worth reading about', ' commonplace river contrary ways remarkable', ' considering missouri main branch longest river world--four miles', ' seems safe crookedest river world part journey uses cover ground crow fly six seventy-five', ' discharges water st', ' lawrence twenty-five rhine thirty-eight thames', ' river vast drainage-basin draws water supply twenty-eight states territories delaware atlantic seaboard country idaho pacific slope spread forty-five degrees longitude', ' mississippi receives carries gulf water fifty-four subordinate rivers navigable steamboats hundreds navigable flats keels', ' area drainage-basin combined areas england wales scotland ireland france spain portugal germany austria italy turkey almost wide region fertile mississippi valley proper exceptionally so']
one_big_string="".join(temp)

print(collections.Counter(one_big_string.split()))

Counter({'river': 4, 'mississippi': 3, 'water': 3, 'drainage-basin': 2、“可导航”:2、“价值”:1、“阅读”:1、“关于”:1、 “普通”:1,“相反”:1,“方式”:1,“卓越”:1, “考虑”:1,“密苏里”:1,“主要”:1,“分支”:1,“最长”:1, 'world--four': 1, 'miles': 1, 'seems': 1, 'safe': 1, 'crookedest': 1, 'world': 1, 'part': 1, 'journey': 1, 'uses': 1, 'cover': 1, 'ground': 1、‘鸦’:1、‘飞’:1、‘六’:1、‘七十五’:1、‘出院’:1、 “st”:1,“劳伦斯”:1,“二十五”:1,“莱茵河”:1,“三十八”: 1,“泰晤​​士河”:1,“广大”:1,“抽奖”:1,“供应”:1,“二十八”:1, “州”:1,“领土”:1,“特拉华州”:1,“大西洋”:1, “海岸”:1,“国家”:1,“爱达荷州”:1,“太平洋”:1,“坡度”:1, “传播”:1,“四十五”:1,“度”:1,“经度”:1, “接收”:1,“携带”:1,“海湾”:1,“五十四”:1, '从属':1,'河流':1,'汽船':1,'数百':1, “平面”:1,“龙骨”:1,“区域”:1,“组合”:1,“区域”:1, “英格兰”:1,“威尔士”:1,“苏格兰”:1,“爱尔兰”:1,“法国”:1, “西班牙”:1,“葡萄牙”:1,“德国”:1,“奥地利”:1,“意大利”:1, “土耳其”:1,“几乎”:1,“宽”:1,“地区”:1,“肥沃”:1, “谷”:1,“适当”:1,“特别”:1,“所以”:1})

【讨论】:

  • 希望我能理解你的问题。您可能还需要遍历您的“唯一”对象,因为将其用作 Counter 为您提供的字典的键
  • 到目前为止我很喜欢,有没有办法在不导入集合的情况下做到这一点?
【解决方案2】:

TL;DR 你的解决方案,但它似乎太复杂了,多次存储行,然后构建 dict 理解,可能会覆盖键,丢失最终的单词数并保留第一个单词数(即 1)。

有一种更短且防失败的方法:您想利用旧的 collections.Counter,但仅限于一些词。

要构建这个过滤计数器,对单词进行迭代,但使用您的唯一列表将它们过滤掉(您构建的 set 非常适合非常有效地过滤掉不需要的单词,让我们保留它):

import collections

c = collections.Counter(word for line in temp for word in line.split() if word in unique)

然后打印它们,排序:

for word,count in sorted(c.items()):
    print("{}: {}".format(word,count))

打印(摘录):

...
reading: 1
receives: 1
region: 1
remarkable: 1
rhine: 1
river: 4
rivers: 1
safe: 1
scotland: 1
seaboard: 1
...

【讨论】:

    【解决方案3】:
    temp = ['mississippi worth reading about', ' commonplace river contrary ways remarkable', ' considering missouri main branch longest river world--four miles', ' seems safe crookedest river world part journey uses cover ground crow fly six seventy-five', ' discharges water st', ' lawrence twenty-five rhine thirty-eight thames', ' river vast drainage-basin draws water supply twenty-eight states territories delaware atlantic seaboard country idaho pacific slope spread forty-five degrees longitude', ' mississippi receives carries gulf water fifty-four subordinate rivers navigable steamboats hundreds navigable flats keels', ' area drainage-basin combined areas england wales scotland ireland france spain portugal germany austria italy turkey almost wide region fertile mississippi valley proper exceptionally so']
    unique = {'longest', 'considering', 'receives', 'water', 'discharges', 'atlantic', 'austria', 'part', 'idaho', 'main', 'drainage-basin', 'st', 'twenty-five', 'seventy-five', 'slope--a', 'world--four', 'remarkable', 'rivers', 'country', 'crookedest', 'areas', 'ireland', 'fifty-four', 'portugal', 'valley', 'france', 'almost', 'branch', 'twenty-eight', 'fertile', 'england', 'crow', 'spread', 'italy', 'journey', 'germany', 'river', 'draws', 'exceptionally', 'scotland', 'fly', 'uses', 'supply', 'region', 'rhine', 'ground', 'thirty-eight', 'thames', 'pacific', 'degrees', 'mississippi', 'lawrence', 'six', 'cover', 'subordinate', 'flats', 'navigable', 'area', 'proper', 'states', 'safe', 'wide', 'territories', 'vast', 'hundreds', 'contrary', 'missouri', 'commonplace', 'gulf', 'worth', 'seaboard', 'steamboats', 'wales', 'turkey', 'combined', 'delaware', 'forty-five', 'carries', 'seems', 'reading', 'keels', 'longitude', 'spain', 'ways'}
    words = dict(zip(list(unique), [0 for i in unique]))
    for str in temp:
        for w in str.split():
            if w in unique:
                words[w] += 1
    
    for a in sorted(words):
        print('{}: {}'.format(a, words[a]))
    

    【讨论】:

    • 我得到 dict() 需要 2 个参数?
    • 我更改了初始化单词的代码。你用的python是什么版本的?
    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2012-04-24
    • 2015-02-20
    • 2022-01-10
    • 2018-10-03
    相关资源
    最近更新 更多