python一段英文统计单词
时间: 2023-07-08 07:53:41 浏览: 62
好的,以下是一个简单的 Python 代码,用于统计英文字符串中单词的个数:
```python
def count_words(s):
"""
统计字符串中单词的个数
"""
s = s.lower() # 转为小写
s = "".join(c if c.isalpha() else " " for c in s) # 只保留字母,其余替换为空格
words = s.split() # 按空格划分单词
return len(words)
s = "This is a test string. It contains some words."
print(count_words(s)) # 输出 8
```
这个函数首先将字符串转为小写,并将所有非字母字符替换为空格。然后按空格划分单词,并统计单词个数。
相关问题
python输入一段英文统计单词个数
可以使用Python中的字符串和列表操作来实现统计英文单词个数的功能。
具体步骤如下:
1. 输入一段英文字符串,可以使用input()函数获取用户输入的字符串。
2. 将字符串转换为列表,可以使用split()函数将字符串按照空格分割成一个列表。
3. 遍历列表,统计单词个数。可以使用for循环遍历列表,使用len()函数获取列表长度,即单词个数。
4. 输出单词个数,可以使用print()函数输出单词个数。
下面是一个示例代码:
```
# 获取用户输入的英文字符串
text = input("请输入一段英文:")
# 将字符串转换为列表
words = text.split()
# 统计单词个数
count = len(words)
# 输出单词个数
print("单词个数为:", count)
```
运行代码后,输入一段英文字符串,程序会输出该字符串中单词的个数。
python英文单词统计代码
以下是Python代码,用于对文本文件中的英文单词进行统计:
```python
import re
from collections import Counter
def count_words(filepath):
with open(filepath, 'r') as file:
# 读取文件内容
text = file.read()
# 使用正则表达式找到所有英文单词
words = re.findall(r'\b\w+\b', text)
# 统计单词数量
word_count = Counter(words)
# 输出结果
print("Total words:", len(words))
print("Unique words:", len(word_count))
print("Top 10 words:")
for word, count in word_count.most_common(10):
print(word, count)
if __name__ == '__main__':
count_words("example.txt")
```
这段代码会打开一个名为“example.txt”的文本文件,并对其中的英文单词进行统计。它使用正则表达式来找到所有单词,然后使用Python的Counter类来统计每个单词的数量。最后,它会输出总单词数、不同单词数和出现次数最多的前10个单词。