以下是一个简单的 Python 代码,可以计算英文文本中的实词数和总单词数:

import re

# 打开文件并读取文本
with open('text.txt', 'r') as file:
    text = file.read()

# 使用正则表达式找到所有的单词
words = re.findall(r'\b\w+\b', text)

# 初始化实词计数器和总单词计数器
content_words = 0
total_words = 0

# 遍历所有单词,判断是否为实词并增加计数器
for word in words:
    if len(word) > 1:  # 排除单个字母的单词
        content_words += 1 if word.lower() not in {'a', 'an', 'the', 'and', 'or', 'but'} else 0
        total_words += 1

# 输出结果
print(f'实词数:{content_words}')
print(f'总单词数:{total_words}')

在这个代码中,我们使用正则表达式 r'\b\w+\b' 找到所有的单词。然后,我们遍历所有的单词,对于每个单词,我们判断它是否为实词(即不是冠词、连词等),并分别增加实词计数器和总单词计数器。最后,我们输出实词数和总单词数。

Python 计算英文文本中的实词和总单词数

原文地址: https://www.cveoy.top/t/topic/oLyT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录