欢迎访问宙启技术站
智能推送

使用Python中的src(源码)创建一个用于文本处理的工具。

发布时间:2023-12-18 02:26:53

下面是一个基于Python的文本处理工具的示例代码,用于处理文本文件中的关键词统计和去除停用词功能。

import re
import string
from collections import Counter


class TextProcessingTool:
    def __init__(self, stopwords_file):
        self.stopwords = set()
        self.load_stopwords(stopwords_file)

    def load_stopwords(self, stopwords_file):
        # 从停用词文件中加载停用词列表
        with open(stopwords_file, 'r', encoding='utf-8') as f:
            for line in f:
                self.stopwords.add(line.strip())

    def remove_punctuation(self, text):
        # 去除文本中的标点符号
        punctuation = string.punctuation + '’“”‘'
        return text.translate(str.maketrans('', '', punctuation))

    def remove_stopwords(self, text):
        # 去除文本中的停用词
        tokens = text.split()
        return ' '.join([w for w in tokens if w.lower() not in self.stopwords])

    def count_keywords(self, text, top_n=10):
        # 统计文本中的关键词出现频率
        text = self.remove_punctuation(text)
        text = self.remove_stopwords(text)
        words = re.findall(r'\w+', text.lower())
        return Counter(words).most_common(top_n)


# 使用例子
if __name__ == '__main__':
    tool = TextProcessingTool('stopwords.txt')

    # 读取文本文件
    with open('text_file.txt', 'r') as f:
        text = f.read()

    # 统计关键词
    keyword_counts = tool.count_keywords(text)
    print('关键词出现频率: ')
    for keyword, count in keyword_counts:
        print(f'{keyword}: {count}')

    # 去除停用词并输出处理后的文本
    processed_text = tool.remove_stopwords(text)
    print('
去除停用词后的文本: ')
    print(processed_text)

上述示例代码中,TextProcessingTool 类封装了文本处理的常用功能。它包含了加载停用词文件、去除标点符号、去除停用词、统计关键词等功能。在使用时,只需要传入停用词文件路径,然后调用相应的函数即可。

在示例中,我们提供了一个 stopwords.txt 文件,其中包含了常见的停用词列表。另外,我们还提供了一个 text_file.txt 文件,作为待处理的文本文件。

你可以根据自己的需要修改或扩展该工具,以满足不同的文本处理需求。