要在Python中搜索和统计文件中词根出现的次数,可以使用以下步骤:
以下是一个完整的示例代码,展示如何在文件中搜索和统计词根出现的次数:
import re
from nltk.stem import PorterStemmer
def read_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
def stem_and_count_words(text, stemmer, target_stem):
# 使用正则表达式分割单词
words = re.findall(r'\b\w+\b', text)
# 初始化计数器
count = 0
for word in words:
stemmed_word = stemmer.stem(word)
if stemmed_word == target_stem:
count += 1
return count
# 主程序
if __name__ == "__main__":
file_path = 'example.txt' # 替换为你的文件路径
target_stem = 'run' # 替换为你想要统计的词根
text = read_file(file_path)
stemmer = PorterStemmer()
count = stem_and_count_words(text, stemmer, target_stem)
print(f"The stem '{target_stem}' appears {count} times in the file.")
read_file
函数读取指定文件的内容。stem_and_count_words
函数使用Porter Stemmer对每个单词进行词干提取,并统计目标词根出现的次数。re.findall(r'\b\w+\b', text)
用于提取文本中的所有单词。open
函数中指定正确的编码。通过上述方法,可以有效地在文件中搜索和统计词根出现的次数。
领取专属 10元无门槛券
手把手带您无忧上云