下面是一个示例程序,根据你的要求计算字符串中每个单词出现的次数,并将结果存储在字典中:
```python
import string
def count_words(text):
# 初始化一个空字典
word_count = {}
# 去除标点符号
translator = str.maketrans('', '', string.punctuation)
text = text.translate(translator)
# 将字符串拆分成单词,并遍历每个单词
for word in text.lower().split():
# 去除单词两端的标点符号
word = word.strip(string.punctuation)
# 如果单词已存在于字典中,则更新对应的出现次数;否则,将单词添加到字典中,并设置出现次数为1
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# 测试程序功能
text = "This is a test string, this is only a test."
result = count_words(text)
print(result)
```
输出结果为:
```
{'this': 2, 'is': 2, 'a': 2, 'test': 2, 'string': 1, 'only': 1}
```