【问题标题】:count the words starts with a-z character using dictionary in python [closed]使用python中的字典计算以a-z字符开头的单词[关闭]
【发布时间】:2015-03-09 07:23:33
【问题描述】:

从以下 url "https://cfstatic.org/static/words.txt" 将字典作为列表加载到 python 中。使用这个单词列表,创建一个 python 字典(如果你使用的是 php,则创建一个数组)

具有以下属性:
键:字母 [a-z]
value:字典中以该字母开头的单词数

我希望结果为

a : number of words start with a 
b : number of words start with b  
[...]
z : number of words start with z

我做了以下,

import urllib2  # the lib that handles the url stuff
try:
    input_file = urllib2.urlopen('https://cfstatic.org/static/words.txt') # it's a file like object and works just like a file
    myNames = []
    for line in input_file:
        myNames.append(line.strip()) #strips the new line in list
    print myNames                      #print the file as list
except urllib2.URLError as e:         #raise the exception if url is not found
    print "Error Message : %s" %e
else:
    print "File reading operation successful!!!"

【问题讨论】:

标签: python list dictionary key-value counting


【解决方案1】:

更改您的 for 循环以创建字典而不仅仅是列表。类似的东西:-

alphabet = {}
for line in input_file:
    line = line.strip()
    starts_with = line[0]
    if line[0] in alphabet:
        alphabet[line[0]].append(line)
    else:
        alphabet[line[0]] = [line]
for key in alphabet:
    alphabet[key] = len(alphabet[key])

正如另一个答案之一所暗示的那样,您也可以这样做(不需要存储元素):-

alphabet = {}
for line in input_file:
    line = line.strip()
    starts_with = line[0]
    if starts_with in alphabet:
        alphabet[starts_with]+= 1
    else:
        alphabet[starts_with] = 1

print alphabet

【讨论】:

  • 嘿@Barun Sharma .. 非常感谢...它有效
【解决方案2】:

collections 模块 (https://docs.python.org/2/library/collections.html#collections.Counter) 中的 Counter 就是为此而生的。

将单词列表转换为第一个字符列表(下面的map(...) 调用),然后将该可迭代直接输入collections.Counter 对象:

>>> import collections                                                                                                                 
>>> words = ["aap", "noot", "mies", "foo", "appel"]                                                                                    
>>> collections.Counter(map(lambda x: x[0], words))                                                                                    
Counter({'a': 2, 'f': 1, 'm': 1, 'n': 1})

【讨论】:

  • 这里不需要 maplambda - 使用 gen-exp 代替... collections.Counter(word[0] for word in words)
  • 也很好 - 任何可以让你产生每个单词的第一个字母的迭代!
  • 确实...但它比 map/lambda 和一致的 2.x/3.x 便宜得多...在 2.x 中 - map 还将构建一个不需要的列表- 只是说:)
【解决方案3】:

我会创建一个带有字母的列表,而不是使用您拥有的单词遍历列表,然后将它们添加到字典中或按以下方式在字典中递增计数器:

letters = [chr(l) for l in range(97,123)]
d = {}
for word in myNames:
    d.update({word[0]: 1}) if not d.has_key(word[0]) else d.update({word[0]: d[word[0]]+1})

我希望这对你有用。如果您需要解释,请写信给我。

【讨论】:

    【解决方案4】:

    我能想到的最简单的是:

    from string import ascii_lowercase
    output_dict = dict.fromkeys(ascii_lowercase, 0)
    input = " this is a text message"
    for ch in input:
        if ch in ascii_lowercase:
            output_dict[ch] += 1
    
    for character, count in output_dict.items():
        if count:
            print "%s : count is %s" % (character, count)
    

    如果你不想使用字符串模块或者想自己减少字符,你可以这样写:

    alphabets_lower = "abcdefghijklmnopqrstuvwxyz"
    output_dict = dict.fromkeys(alphabets_lower, 0)
    

    玩得开心:-)

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 2018-09-03
      • 2020-07-28
      • 2013-05-24
      • 2016-01-13
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多