在Python中,你可以使用 `split()` 方法将字符串分割成单词列表,然后使用 `len()` 函数统计单词的个数。下面是一个简单的示例代码:
```python
获取用户输入的字符串
text = input("请您输入一串字符串: ")
去除字符串前后的空格
text = text.strip()
使用split()方法分割字符串为单词列表
words = text.split()
计算单词个数
word_count = len(words)
输出单词个数
print("输入的字符串中一共有 %d 个单词" % word_count)
如果你需要从文件中读取文本并统计单词数,可以使用以下代码:
```python
打开文件并读取内容
with open('file_path.txt', 'r', encoding='utf-8') as file:
text = file.read()
清洗文本,去除标点符号
text = re.sub(r'[^\w\s]', '', text)
分割文本为单词列表
words = text.split()
使用Counter统计单词频率
from collections import Counter
word_count = Counter(words)
输出单词个数
print("单词个数:", len(word_count))
请根据你的需求选择合适的方法。