给定一个字符串,编写一个python程序,计算其中每个单词出现的次数,并将结果存储在一个字典中。要求忽略单词间的大小写差异和标点符号。 提示:可以使用python的split函数将字符串拆分成单词,使用lower函数将单词转换为小写,使用strip函数去除单词两端的标点符号,然后使用字典的赋值语法将单词添加到字典中,并更新它们的出现次数

下面是一个示例程序,根据你的要求计算字符串中每个单词出现的次数,并将结果存储在字典中:

```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}
```

相关代码参考