PAT 1071 Speech Patterns python解法

1071 Speech Patterns (25 分)
People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.

Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

Input Specification:
Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return \n. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].

Output Specification:
For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a “word” is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.

Note that words are case insensitive.

Sample Input:
Can1: “Can a can can a can? It can!”
Sample Output:
can 5

题意:统计一句话中出现最多的单词和次数,相同次数时输出字典序小的。

解题思路:
1.导入re用来匹配单词,collections.Counter用来计数。
2.最后输出的结果不区分大小写,可以先把输入的字符s转换为小写。
3.使用re对s进行匹配,获得一个单词列表list1。
4.使用Counter对list1中单词进行计数,并将结果转换为字典形式。
5.用list2存列表形式的字典键值对。
6.根据单词和次数对列表排序,获取最后一个键值对并输出。
注:
dict1的格式如:{‘it’: 1, ‘can1’: 1, ‘a’: 2, ‘can’: 5}
list2的格式如:[(‘can1’, 1), (‘can’, 5), (‘a’, 2), (‘it’, 1)]
lambda x:(not x[0],x[1])中,not x[0]指的是对list2先对第一维数据升序(因为’a’ < ‘z’)不加not则为降序。

import re
from collections import Counter
s = input()
#s = 'Can1: "Can a can can a can?  It can!"'
s = s.lower()
list1 = re.findall('[0-9|a-z]+', s)
dict1 = dict(Counter(list1))
list2 = list(dict1.items())
out = sorted(list2,key = lambda x:(not x[0],x[1]))[-1]
print(out[0],out[1])

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/87720340