Exercism: Word Count (Python)

统计一句话中单词的数量。可以直接使用collecitons中的Counter。稍微麻烦的是句子需要parse一下。我试着用正规表达式,不过没法全部做到处理全部规则。等通过后看看有没有其他人可以做到。

from collections import Counter
import re


def count_words(sentence):
    words = re.findall(r"([\w]+'*[\w]*)+\b", sentence.replace("_", " ").lower())
    return dict(Counter(words))

Updated: 19/08/2020 刚看了导师的评论,推荐不用re和dict Counter。直接写parser还有点费劲,要考虑到不同的case。

import re


class Counter:

    def __init__(self):
        self.__counter = {}
    
    def count(self, word):
        self.__counter.setdefault(word, 0)
        self.__counter[word] += 1
    
    @property
    def data(self):
        return self.__counter


def count_words(sentence):
    #words = sentence.lower().replace(",", " ").replace(".", " ").split(" ")
    counter = Counter()
    word = ""
    start_word = False
    quote_level = 0
    escape = False
    for c in sentence: 
        if escape:
            escape = False
        elif c == "\\":
            escape = True
        elif c.isalnum():
            word += c.lower()
            start_word = True
        elif c == "'":
            if not start_word:
                quote_level += 1 
            elif quote_level > 0 and start_word:
                quote_level -= 1 
            else:
                word += c
        else:
            if word:
                counter.count(word)
                word = ""
                start_word = False
    if word:
        counter.count(word)
    return counter.data 

评论

此博客中的热门博文

拜厄练习曲44, 45

拜厄练习曲38, 39