经过顺利通关入门岛的第一关,已经对InternStudio开发机及Linux操作系统有了初步的认识。接下来,将开始继续第二关——Python编程挑战。
0 Python实现wordcount
首先,使用Vscode的ssh功能连接至开发机。接着,借助Vscode内置的终端工具,创建一个demos目录。在此目录中,我们将新建一个名为wordcount.py的文件,并实现以下任务代码编写:
请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。
import re
def process_text(text: str):
"""
对文本进行处理,将其转化为小写,移除特殊字符并用空格替换,最后返回单词列表。
Args:
text (str): 待处理的文本字符串。
Returns:
List[str]: 处理后的单词列表。
"""
if text is None or text == "":
return []
return re.sub("[\W]+", " ", text.lower()).split()
def statistics(words: str):
"""
统计字符串中每个单词出现的次数
Args:
words (str): 需要统计的字符串
Returns:
dict: 字典类型,键为单词,值为单词出现的次数
"""
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts
def wordcount(text: str):
"""
计算给定文本中单词的数量。
Args:
text (str): 待计算单词数量的文本字符串。
Returns:
int: 文本中单词的数量。
"""
new_text = process_text(text)
return statistics(new_text)
if __name__ == "__main__":
text = """
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.
"""
print(wordcount(text))

1 Vscode连接InternStudio Debug
首先,在代码编辑窗口中,代码的关键行上设置断点,以便于调试。完成断点设置后,在Vscode左侧的工具栏,点击虫子图标。接下来,选择“运行和调试”选项,启动Debug模式。




被折叠的 条评论
为什么被折叠?



