有一篇文章,共有3行文字,每行小于80个字符。要求分别统计出其中英文大写字母、小写字母、数字、空格以及其他字符的个数
时间: 2023-04-24 18:05:25 浏览: 70
可以使用 Python 中的字符串方法和正则表达式来实现统计。例如:
```python
import re
text = "This is a text with 3 lines. 123"
uppercase = len(re.findall(r"[A-Z]", text))
lowercase = len(re.findall(r"[a-z]", text))
numbers = len(re.findall(r"[0-9]", text))
spaces = len(re.findall(r"\s", text))
others = len(re.findall(r"[^A-Za-z0-9\s]", text))
print("Uppercase: ", uppercase)
print("Lowercase: ", lowercase)
print("Numbers: ", numbers)
print("Spaces: ", spaces)
print("Others: ", others)
```
上面代码使用正则表达式来匹配大写字母、小写字母、数字、空格和其他字符,并使用 len() 方法来计算每种字符的个数。
对于文本文件中的文章,可以使用 python 的文件读取函数来读取文件中的文本,然后对文本进行上面的处理。
如果文章文件名为 “article.txt” 可以使用下面的代码读取文件中的文本,并进行统计:
```python
with open("article.txt", "r") as f:
text = f.read()
uppercase = len(re.findall(r"[A-Z]", text))
lowercase = len(re.findall(r"[a-z]", text))
numbers = len(re.findall(r"[0-9]", text))
spaces = len(re.findall(r"\s", text))
others = len(re.findall(r"[^A-Za-z0-9\s]", text))
print("Uppercase: ", uppercase)
print("Lowercase: ", lowercase)
print("Numbers: ", numbers)
print("Spaces: ", spaces)
print("Others: ", others)
```
如果需要统计每行的字符数,可以使用 python 的 splitlines() 函数将文本按行分割成列表,然后对每行使用上述方法进行统计。例如:
```python
with open("article.txt", "r") as f:
text = f.read()
lines = text.splitlines()
for line in lines:
uppercase = len(re.findall(r"[A-Z]", line))
lowercase = len(re.findall(r"[a-z]", line))
numbers = len(re.findall(r"[0-9]", line))
spaces = len(re.findall(r"\s", line))
others = len(re.findall(r"[^A-Za-z0-9\s]", line))
print("Line: ", line)
print("Uppercase: ", uppercase)
print("Lowercase: ", lowercase)
print("Numbers: ", numbers)
print("Spaces: ", spaces)
print("Others: ", others)
```
通过这样的方式可以得到每一行的字符统计。