python建立字典读取键和值_在Python字典中动态创建键和值

在Python2中,我会做这样的事情。。。在#! /usr/bin/env python

'''

Count vowels in a list of words & show a grand total

Words come from a plain text file with one word per line

'''

import sys

vowels = 'aeiouy'

def make_count_dict():

''' Create a dict for counting vowels with all values initialised to 0 '''

return dict(zip(vowels, (0,)*len(vowels)))

def get_counts(d):

return ' '.join('%2d' % d[k] for k in vowels)

def count_vowels(wordlist):

hline = '_'*45

print '%3s: %-20s: %s' % ('Num', 'Word', ' '.join('%2s' % v for v in vowels))

print hline

total_counts = make_count_dict()

for num, word in enumerate(wordlist, start=1):

word_counts = make_count_dict()

for ch in word.lower():

if ch in vowels:

word_counts[ch] += 1

total_counts[ch] += 1

print '%3d: %-20s: %s' % (num, word, get_counts(word_counts))

print hline

print '%-25s: %s' % ('Total', get_counts(total_counts))

def main():

fname = len(sys.argv) > 1 and sys.argv[1]

if fname:

try:

with open(fname, 'r') as f:

wordlist = f.read().splitlines()

except IOError:

print "Can't find file '%s'; aborting." % fname

exit(1)

else:

wordlist = ['Mississippi', 'California', 'Wisconsin']

count_vowels(wordlist)

if __name__ == '__main__':

main()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部