已知文件,统计文件中某行单词有多少种,,不算标点符号,单词是英文单词,写一段python代码
时间: 2024-03-08 08:50:16 浏览: 25
可以使用Python中的正则表达式和集合(set)来实现这个功能。具体代码如下:
```python
import re
def count_words(line):
# 使用正则表达式匹配所有的单词
words = re.findall(r'\b\w+\b', line)
# 使用集合去重,统计单词种类数
return len(set(words))
# 读取文件内容
with open('file.txt', 'r') as f:
content = f.readlines()
# 统计每行单词种类数
for line in content:
count = count_words(line)
print(f'Line "{line.strip()}" has {count} different words.')
```
其中,`count_words`函数使用正则表达式`\b\w+\b`匹配所有的单词,并使用集合去重后返回单词种类数。在主程序中,读取文件内容后,逐行统计单词种类数并输出结果。
相关问题
C语言程序编写,已知文件dict.txt中存储一段由若干个单词组成的文本,统计出该文本中单词的数量及标点符号的数量(分隔单词的空格不算在内)。
可以按照以下步骤进行:
1. 打开文件dict.txt,判断是否成功打开。
2. 定义变量`word_count`和`punct_count`分别表示单词数量和标点符号数量,初始化为0。
3. 读取文件中的每一个字符,如果是空格或换行符,则说明一个单词结束,将`word_count`加1;如果是标点符号,则将`punct_count`加1。注意要排除空格的计数。
4. 关闭文件。
5. 输出单词数量和标点符号数量。
具体实现的代码如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp = fopen("dict.txt", "r");
if (fp == NULL) {
printf("Failed to open file dict.txt\n");
return 1;
}
int word_count = 0, punct_count = 0;
char c, prev = '\0';
while ((c = fgetc(fp)) != EOF) {
if (isspace(c) || c == '\n') {
if (!isspace(prev) && prev != '\0') {
word_count++;
}
} else if (ispunct(c)) {
punct_count++;
}
prev = c;
}
fclose(fp);
printf("The text contains %d words and %d punctuation marks\n", word_count, punct_count);
return 0;
}
```
在这个程序中,我们使用了`fopen`函数打开了`dict.txt`文件,并以只读模式打开。然后,我们定义了变量`word_count`和`punct_count`分别表示单词数量和标点符号数量,并初始化为0。接着,我们使用`fgetc`函数逐个读取文件中的字符。如果这个字符是空格或换行符,则说明一个单词结束,我们就将`word_count`加1;如果这个字符是标点符号,则将`punct_count`加1。注意到如果前面的字符不是空格或换行符,我们才将`word_count`加1。最后,我们使用`fclose`函数关闭文件,并输出单词数量和标点符号数量。
用Python写一个程序,找出已知字符串s中的最长单词
可以使用以下代码实现:
```python
s = "This is a sample string"
words = s.split()
longest_word = max(words, key=len)
print("The longest word in the string is:", longest_word)
```
输出结果为:
```
The longest word in the string is: sample
```
这个程序将字符串s分割成单词列表,然后使用max函数找出列表中最长的单词。