# 02.入门岛-第二关Python基础知识

# 1.Python实现wordcount

import string


def strip_punctuation(text):
    return "".join([c for c in text if c not in string.punctuation])


def count_words(input: str):
    if not input:
        return None

    input = strip_punctuation(input)
    words = input.replace("\n", " ").lower().split(" ")
    word_dict = {}

    for w in words:
        if len(w.strip()) <= 0:
            continue

        if w in word_dict.keys():
            word_dict[w] = word_dict[w] + 1
        else:
            word_dict[w] = 1

    return word_dict


if __name__ == "__main__":
    input = """Hello world!
    This is an example.  Word count is fun. Is it fun to count words?  Yes, it is fun!"""
    res = count_words(input)
    print(f"input:{input}")
    print(f"output:{res}")
    print("---------------------------------")
    # case2
    case_2_input = """
        Got this panda plush toy for my daughter's birthday,
        who loves it and takes it everywhere. It's soft and
        super cute, and its face has a friendly look. It's
        a bit small for what I paid though. I think there
        might be other options that are bigger for the
        same price. It arrived a day earlier than expected,
        so I got to play with it myself before I gave it
        to her.
        """
    res = count_words(case_2_input)
    print(f"input:{case_2_input}")
    print(f"output:{res}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

output image

# 2.Vscode连接InternStudio debug笔记

安装要vscode推荐的插件,直接debug run,就可以进行debug。 image

Last Updated: 7/13/2024, 7:49:06 PM
Apache License 2.0 | Copyright © 2022 by xueliang.wu 苏ICP备15016087号