首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python 发个题目不太明白要如何整啊

2013-07-09 
python 发个题目不太明白要怎么整啊?Write a program which will ask the user to enter a bunch of text

python 发个题目不太明白要怎么整啊?
Write a program which will ask the user to enter a bunch of text at the keyboard (ie several lines, each having several words per line), and then analyse the text. The 'analysis' will comprise finding the most common and least common non-space characters (note that there may be several characters having the same frequency of occurrence).
[解决办法]
让用户输入多行字符,然后找到最多和最少的字符,最多或者最小的字符可能有多个

# ask for input
text = []
print 'Please input text: (ENTER for break)'
while True:
    line = raw_input().strip()
    if not line: break
    text.append(line)    

# analysis
import string
all_text = [x for x in ''.join(text) if x in string.ascii_letters]
freq_letter = {x:all_text.count(x) for x in all_text}
max_letter = [k for k,v in freq_letter.items() if v==max(freq_letter.values())]
min_letter = [k for k,v in freq_letter.items() if v==min(freq_letter.values())]

# output
print 'the most common character(s):', max_letter
print 'the least common character(s):', min_letter

测试结果:
>>> ================================ RESTART ================================
>>> 
Please input text: (ENTER for break)
a b c b a a d

the most common character(s): ['a']
the least common character(s): ['c', 'd']
>>> 

[解决办法]
from collections import Counter
text='A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'


c=Counter(text)
d={x:c[x] for x in c if ord(x) in range(33,127)}
print('most:', sorted([x for x in d if d[x]==max(d.values())]))
print('most:', sorted([x for x in d if d[x]==min(d.values())]))


键盘输入的部分自己改改吧

热点排行