示例代码如下:
s = "hello world, hello python"
# 将字符串分割成单词列表
words = s.split()
# 使用字典统计每个单词的出现次数
freq = {}
for word in words:
if word not in freq:
freq[word] = 1
else:
freq[word] += 1
# 输出结果
for word, count in freq.items():
print(word, count)
输出:
hello 2
world, 1
python 1