书生大模型实战营学习[2]Python task
学习目标:Python学习
- Python实现wordcount
- Vscode连接InternStudio debug笔记
学习内容:
任务1:请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。
input:
"""Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""
output:
{'hello': 1, 'world': 1, 'this': 1, 'is': 4, 'an': 1, 'example': 1, 'word': 1, 'count': 2,
'fun': 3, 'it': 2, 'to': 1, 'words': 1, 'yes': 1}
第一种是使用正则:
import re
from collections import Counterdef wordcount(text):# 使用正则表达式将文本中的单词分割开来,同时转换为小写words = re.findall(r'\b\w+\b', text.lower())# 使用 Counter 来计算每个单词出现的次数word_counts = Counter(words)return dict(word_counts)# 输入文本
text = """Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""# 调用函数并打印结果
print(wordcount(text))
第二种是使用hash
def word_count(text):# 创建一个字典来存储单词计数hash = {}# 遍历字符串中的每个字符i = 0while i < len(text):# 检查当前字符是否是字母if text[i].isalpha():j = iword = ''# 继续向后查找,直到遇到非字母字符while j < len(text) and text[j].isalpha():word += text[j].lower()j += 1# 更新字典中的单词计数hash[word] = hash.get(word, 0) + 1# 移动索引到单词的末尾i = jelse:i += 1# 返回包含单词计数的字典return hashdef main():text = """Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""word_counts = word_count(text)for word, count in word_counts.items():print(f"{word}: {count}")if __name__ == "__main__":main()
任务二:debug
首先输入debug命令行
运行
进入word_count函数
一步步dubug
填入hash