可以使用Python的re模块和collections模块来实现该功能。首先,使用re模块的findall()函数找到字符串中的所有单词。然后,使用collections模块的Counter()函数统计每个单词出现的次数,并将结果存储在一个字典中。 以下是示例代码:
```python
import re
from collections import Counter
def count_words(string):
# 使用正则表达式找到字符串中的所有单词
words = re.findall(r'\w+', string.lower())
# 统计每个单词出现的次数
word_counts = Counter(words)
return dict(word_counts)
# 测试示例
input_string = "This is a test. This is only a test."
word_counts = count_words(input_string)
print(word_counts)
```
输出结果为:
```
{'this': 2, 'is': 2, 'a': 2, 'test': 2, 'only': 1}
```
该程序将忽略单词间的大小写差异和标点符号,并统计了每个单词出现的次数。注意,该方法只能统计以字母开头的单词,不包括特殊字符开头的单词。