写一段程序统计文本文件(纯英文)的字符数或者单词数。
时间: 2023-06-13 10:02:58 浏览: 69
以下是Python的代码示例,可以统计文本文件中的字符数和单词数:
```python
import string
# 打开文件并读取内容
with open('filename.txt', 'r') as file:
content = file.read()
# 统计字符数
char_count = len(content)
# 统计单词数
word_count = len(content.split())
# 移除标点符号
translator = str.maketrans('', '', string.punctuation)
content_without_punct = content.translate(translator)
# 统计单词数(去除标点符号后)
word_count_without_punct = len(content_without_punct.split())
# 输出结果
print("字符数:", char_count)
print("单词数:", word_count)
print("去除标点符号后的单词数:", word_count_without_punct)
```
注意:这段代码仅适用于纯英文文本文件,对于含有其他语言或特殊字符的文件可能需要做出一些修改。
相关问题
写一段C语言程序程序统计文本文件(纯英文)的字符数或者单词数。
以下是统计文本文件字符数和单词数的C语言程序:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp;
char filename[1000], ch;
int characters = 0, words = 0;
printf("Enter the filename: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 0;
}
while ((ch = fgetc(fp)) != EOF) {
characters++;
if (isspace(ch)) {
words++;
}
}
fclose(fp);
printf("Characters: %d\n", characters);
printf("Words: %d\n", words + 1);
return 0;
}
```
这个程序会要求用户输入要统计的文本文件的文件名,然后打开文件并逐个字符读取。每遇到一个空格,就会认为前面的一段文字是一个单词,单词数就会加一。最后输出统计结果:字符数和单词数(单词数加一是因为最后一个单词后面没有空格)。
编写程序统计一个文本文件中的字符数,单词数以及行数,单词由空格分隔(假设没有标点符号)。用python
好的,可以使用Python来完成这个任务。下面是代码实现:
```python
with open('filename.txt', 'r', encoding='utf-8') as f:
# 统计字符数
char_count = 0
for line in f:
char_count += len(line)
print('字符数:', char_count)
with open('filename.txt', 'r', encoding='utf-8') as f:
# 统计单词数
word_count = 0
for line in f:
words = line.split()
word_count += len(words)
print('单词数:', word_count)
with open('filename.txt', 'r', encoding='utf-8') as f:
# 统计行数
line_count = 0
for line in f:
line_count += 1
print('行数:', line_count)
```
代码解析:
1. 使用Python内置的open函数打开文件,并利用with语句实现文件的自动关闭。
2. 第一段代码统计文件中的字符数,使用一个计数器char_count来记录所有行的字符总数,每次遍历一行就累加该行的字符数。
3. 第二段代码统计文件中的单词数,使用一个计数器word_count来记录所有行的单词总数,对每一行进行split操作,将一行的内容拆分成一个个单词,然后累加所有行的单词数。
4. 第三段代码统计文件中的行数,使用一个计数器line_count来记录文件中的行数,每次遍历一行就累加1。
希望这个代码可以帮到你!