python输入一个英文字符串,统计英文单词的个数
时间: 2023-11-16 08:24:18 浏览: 53
好的,以下是一个简单的 Python 代码示例,可以用来统计字符串中英文单词的个数:
```python
def count_words(text):
# 将字符串转换为小写字母,方便后面统计单词
text = text.lower()
# 将字符串中的标点符号替换为空格,方便后面分割单词
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = text.replace(ch, ' ')
# 使用 split 方法分割单词
words = text.split()
# 返回单词列表长度
return len(words)
# 测试代码
text = "This is a test sentence. There are 8 words in this sentence."
print(count_words(text)) # 输出 8
```
这段代码首先将字符串转换为小写字母,然后将字符串中的标点符号替换为空格。接着使用 `split()` 方法分割单词,最后返回单词列表长度即可。
相关问题
输入一个英文字符串 编写程序 统计英文单词个数 python
好的,以下是一个简单的 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 代码示例,可以用来统计字符串中英文单词的个数:
```python
import re
def count_words(text):
# 使用正则表达式匹配英文单词
pattern = r'\b[A-Za-z]+\b'
# 使用 findall 方法找到所有匹配的单词
words = re.findall(pattern, text)
# 返回单词列表长度
return len(words)
# 测试代码
text = "This is a test sentence. There are 8 words in this sentence."
print(count_words(text)) # 输出 8
```
这段代码使用了 Python 的 `re` 模块来进行正则表达式匹配,匹配规则使用了一个简单的正则表达式 `\b[A-Za-z]+\b`,表示匹配以字母开头,由字母组成的单词。然后使用 `findall` 方法找到所有匹配的单词,最后返回列表长度即可。