脚本如何自动给文本内容打标

wen 实用脚本 30

本文目录导读:

脚本如何自动给文本内容打标

  1. 基于规则的匹配方法
  2. 使用正则表达式
  3. 使用机器学习/深度学习
  4. 使用开源库
  5. 完整的自动打标系统
  6. 使用API服务
  7. 建议的实践方案

基于规则的匹配方法

关键词匹配

import re
def keyword_tagging(text):
    tags = []
    # 定义规则
    rules = {
        '科技': ['AI', '人工智能', '编程', '代码'],
        '财经': ['股票', '投资', '理财', '基金'],
        '体育': ['足球', '篮球', '奥运', '世界杯'],
        '娱乐': ['电影', '音乐', '明星', '综艺']
    }
    for tag, keywords in rules.items():
        for keyword in keywords:
            if keyword in text:
                tags.append(tag)
                break
    return tags

使用正则表达式

import re
def regex_tagging(text):
    patterns = {
        '邮箱': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        '电话': r'1[3-9]\d{9}',
        '网址': r'https?://[^\s]+',
        '日期': r'\d{4}-\d{2}-\d{2}'
    }
    tags = []
    for tag, pattern in patterns.items():
        if re.search(pattern, text):
            tags.append(tag)
    return tags

使用机器学习/深度学习

使用预训练模型

from transformers import pipeline
classifier = pipeline("zero-shot-classification")
def ml_tagging(text, candidate_labels):
    result = classifier(text, candidate_labels)
    # 返回置信度最高的标签
    tags = []
    for label, score in zip(result['labels'][:3], result['scores'][:3]):
        if score > 0.5:  # 设置阈值
            tags.append(label)
    return tags

使用开源库

Jieba分词 + TF-IDF

import jieba
from jieba import analyse
def tfidf_tagging(text, topK=5):
    # 提取关键词
    keywords = analyse.extract_tags(text, topK=topK)
    return keywords

TextRank算法

from jieba import analyse
def textrank_tagging(text, topK=5):
    textrank = analyse.TextRank()
    keywords = textrank.keywords(text, topK=topK)
    return keywords

完整的自动打标系统

class AutoTagger:
    def __init__(self):
        self.rules = {}
        self.ml_model = None
    def add_rule(self, tag, keywords):
        """添加基于规则的标签"""
        self.rules[tag] = keywords
    def rule_based_tag(self, text):
        """规则匹配打标"""
        tags = []
        for tag, keywords in self.rules.items():
            for keyword in keywords:
                if keyword in text:
                    tags.append(tag)
                    break
        return tags
    def ml_based_tag(self, text, candidates):
        """机器学习打标"""
        # 使用预训练模型
        from transformers import pipeline
        classifier = pipeline("zero-shot-classification")
        result = classifier(text, candidates)
        return [label for label, score in zip(result['labels'], result['scores']) if score > 0.5]
    def hybrid_tag(self, text, ml_candidates=None):
        """混合打标"""
        tags = set()
        # 规则匹配
        rule_tags = self.rule_based_tag(text)
        tags.update(rule_tags)
        # 机器学习
        if ml_candidates:
            ml_tags = self.ml_based_tag(text, ml_candidates)
            tags.update(ml_tags)
        return list(tags)
# 使用示例
tagger = AutoTagger()
tagger.add_rule('技术', ['Python', '编程', '开发'])
tagger.add_rule('AI', ['人工智能', '机器学习', '深度学习'])
text = "Python在人工智能和机器学习领域应用广泛"
tags = tagger.hybrid_tag(text, ['技术', 'AI', '商业', '教育'])
print(f"标签: {tags}")

使用API服务

百度AI、阿里云等

import requests
def api_tagging(text, api_key, secret_key):
    url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword"
    # 获取access_token
    token_url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}"
    response = requests.post(url, json={
        'text': text,
        'top_num': 5
    }, params={'access_token': token_url})
    return response.json()

建议的实践方案

  1. 简单场景:使用规则匹配 + 关键词库
  2. 中等场景:规则 + TF-IDF/TextRank
  3. 复杂场景:使用预训练模型或API服务
  4. 工业场景:结合多种方法,形成标签体系

需要根据具体的数据量、准确度要求、实时性要求来选择合适的方法。

抱歉,评论功能暂时关闭!