字符串-LeetCode819-Most Common Word

题意:将整句话的单词都变成小写,去掉符号,去掉banned中的词。统计剩下词的词频,返回词频最高的单词。
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"

class Solution(object):
    def mostCommonWord(self, paragraph, banned):

        """
        :type paragraph: str
        :type banned: List[str]
        :rtype: str
        """

        from collections import Counter
        symble = re.compile(r"[!?',;.]")
        new_paragraph = symble.sub('', paragraph.lower())
        words = new_paragraph.split(' ')
        words = [word for word in words if word not in banned]
        count = Counter(words)
        return count.most_common(1)[0][0]

首先导入Counter,然后去掉符号同时变成小写。之后切割成词,在去掉banned中的词。用Counter统计词频,返回词频最高的词。

猜你喜欢

转载自blog.csdn.net/sjzuliguoku/article/details/81950100