python拆分句子、去除句子符号等并分词

本文介绍了如何使用Python中的正则表达式、nltk库和jieba分词工具对文本进行拆分,按指定长度批量处理,并进行HTML标签、链接、特殊字符和停用词的清洗,以得到干净的中文文本数据。
摘要由CSDN通过智能技术生成
import re

def split_text_into_batches(text, max_tokens_per_batch):
    # 定义一个正则表达式,在中文标点符号处拆分句子
    sentence_splitter = re.compile(r'(?<=[。!?])')

    # 将文本拆分为句子
    sentences = [sentence.strip() for sentence in sentence_splitter.split(text) if sentence.strip()]

    # 初始化变量
    batches = []
    current_batch = ""

    for sentence in sentences:
        if len(current_batch) + len(sentence) <= max_tokens_per_batch:
            current_batch += sentence + " "
        else:
            # 找到距离 max_tokens_per_batch 限制最近的标点符号
            last_punctuation_index = max(current_batch.rfind('。'), current_batch.rfind('!'), current_batch.rfind('?'))

            # 如果限制范围内没有标点符号,就在最后一个空格处拆分
            split_index = last_punctuation_index if last_punctuation_index != -1 else current_batch.rfind(' ')

            # 将批次添加到拆分索引处
            batches.append(current_batch[:split_index].strip())

            # 新批次从拆分索引开始
            current_batch = sentence + " "

    if current_batch.strip():  # 确保不将空字符串添加到批次中
        batches.append(current_batch.strip())

    return batches

text = ""

max_tokens_per_batch = 20
batches = split_text_into_batches(text, max_tokens_per_batch)
print("Batches:", batches)
import re
import nltk
import jieba
nltk.download('punkt')
import string
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def clean_html_tags(text):
    clean_text = re.sub(r'<.*?>', '', text)
    return clean_text

def remove_links(text):
    clean_text = re.sub(r'http\S+', '', text)
    return clean_text

def remove_special_characters(text):
    clean_text = ''.join(char for char in text if char not in string.punctuation)
    return clean_text

def remove_extra_whitespace(text):
    clean_text = ' '.join(text.split())
    return clean_text

def remove_stopwords(text):
    stop_words = set(stopwords.words('english'))
    word_tokens = word_tokenize(text)
    clean_text = ' '.join(word for word in word_tokens if word.lower() not in stop_words)
    return clean_text

def clean_chinese_text(text):
    # 清除HTML标签
    cleaned_text = clean_html_tags(text)

    # 去除链接
    cleaned_text = remove_links(cleaned_text)

    # 去除特殊字符
    cleaned_text = remove_special_characters(cleaned_text)

    # 去除额外的空白
    cleaned_text = remove_extra_whitespace(cleaned_text)

    # 去除停用词
    cleaned_text = remove_stopwords(cleaned_text)
    # 使用jieba进行分词
    word_list = jieba.lcut(cleaned_text)

    # 拼接成清洗后的文本
    cleaned_text = ' '.join(word_list)

    return cleaned_text

input_text =""

cleaned_text = clean_chinese_text(input_text)
print(cleaned_text)

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在Python中,可以使用自然语言处理工具库NLTK(Natural Language Toolkit)或者spaCy来计算句子之间的相似度。这里简单介绍一下使用NLTK计算句子相似度的方法。 NLTK提供了多种用于计算文本相似度的算法,其中最常用的是基于词袋模型的余弦相似度算法。该算法首先将两个句子分别转化为向量表示,然后计算这两个向量之间的余弦相似度。 下面是一个简单的示例代码,演示如何使用NLTK计算两个句子的相似度: ```python from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.stem import WordNetLemmatizer from nltk import ne_chunk from nltk.metrics import * from string import punctuation def clean_text(text): # 去除标点符号 text = ''.join([c for c in text if c not in punctuation]) # 分词 tokens = word_tokenize(text) # 去除停用词 stop_words = set(stopwords.words('english')) tokens = [w for w in tokens if not w.lower() in stop_words] # 词形还原 lemmatizer = WordNetLemmatizer() tokens = [lemmatizer.lemmatize(w) for w in tokens] # 命名实体识别 ne_chunks = ne_chunk(pos_tag(tokens), binary=True) named_entities = set(' '.join(i[0] for i in ne) for ne in ne_chunks if isinstance(ne, nltk.tree.Tree)) return named_entities def cosine_similarity(text1, text2): # 清洗文本 named_entities1 = clean_text(text1) named_entities2 = clean_text(text2) # 构建词袋 all_words = list(set(named_entities1).union(set(named_entities2))) vector1 = [1 if w in named_entities1 else 0 for w in all_words] vector2 = [1 if w in named_entities2 else 0 for w in all_words] # 计算余弦相似度 return round(1 - cosine_distance(vector1, vector2), 2) ``` 在上面的代码中,`clean_text()`函数用于清洗文本,并提取其中的命名实体。`cosine_similarity()`函数则用于计算两个句子的相似度,其中使用了NLTK的`cosine_distance()`函数来计算余弦相似度。 使用示例: ```python text1 = "I like to eat apples." text2 = "Apples are my favorite fruit." similarity_score = cosine_similarity(text1, text2) print(similarity_score) # 输出:0.29 ``` 注意,以上代码仅仅是一个简单的示例,实际应用中需要根据具体场景对代码进行优化和改进。 ### 回答2: 在Python中,可以使用自然语言处理库如NLTK(Natural Language Toolkit)或者spaCy来判断句子之间的相似度。 首先,需要将句子进行分词处理。NLTK和spaCy都提供了现成的分词器,可以将句子拆分成单词或者词语。分词之后,可以通过去除停用词(如‘的’、‘了’等)来减少噪音。 然后,可以将每个单词转换为词向量表示。Word2Vec是一种常用的词向量模型,可以将单词映射为在向量空间中的表示。可以使用已经训练好的Word2Vec模型,也可以根据自己的数据进行训练。 接下来,可以使用余弦相似度来衡量两个句子之间的相似度。余弦相似度将两个向量之间的夹角度量为0到1之间的一个值,数值越接近1代表相似度越高。 最后,根据相似度进行判断。可以设定一个阈值,当两个句子的相似度大于阈值时判断为相似,否则判断为不相似。 实现相似度判断的代码如下所示(使用NLTK和Word2Vec): ```python from nltk.tokenize import word_tokenize from gensim.models import Word2Vec from scipy import spatial # 加载Word2Vec模型 model = Word2Vec.load('word2vec_model') # 定义余弦相似度函数 def cosine_similarity(vec1, vec2): return 1 - spatial.distance.cosine(vec1, vec2) # 定义句子相似度判断函数 def sentence_similarity(sentence1, sentence2): # 分词 tokens1 = word_tokenize(sentence1) tokens2 = word_tokenize(sentence2) # 移除停用词 stop_words = set(['的', '了', '是', '在', ...]) # 自定义停用词 tokens1 = [w for w in tokens1 if not w in stop_words] tokens2 = [w for w in tokens2 if not w in stop_words] # 转换为词向量 vectors1 = [model.wv[word] for word in tokens1 if word in model.wv] vectors2 = [model.wv[word] for word in tokens2 if word in model.wv] # 计算平均向量 if len(vectors1) > 0 and len(vectors2) > 0: avg_vector1 = sum(vectors1) / len(vectors1) avg_vector2 = sum(vectors2) / len(vectors2) # 计算余弦相似度 similarity = cosine_similarity(avg_vector1, avg_vector2) return similarity else: return 0 # 测试 sentence1 = '我喜欢吃苹果' sentence2 = '苹果是我喜欢吃的水果' similarity = sentence_similarity(sentence1, sentence2) print('句子相似度:', similarity) ``` 请注意,具体的实现方法还要根据具体的需求和数据来进行调整和优化,例如可以考虑使用更复杂的模型(如BERT)或者加入其他特征来提高相似度判断的准确度。 ### 回答3: Python可以利用自然语言处理技术根据语义判断句子之间的相似度。在这个过程中,可以使用一种称为词向量的技术,将句子转换为数值表示,这样可以更好地比较它们之间的相似度。 在python中,我们可以使用一些常用的库来实现这个目标。其中最著名的是使用Word2Vec模型的gensim库。通过使用预训练的Word2Vec模型,我们可以将每个句子中的单词转换为对应的词向量,然后将这些词向量求平均,得到整个句子的向量。接下来,我们可以使用余弦相似度或欧几里德距离等方法来比较不同句子之间的向量相似度。 除了gensim库,还有其他一些库可以用来计算句子之间的相似度,如spaCy和nltk。这些库提供了一些现成的工具和算法来处理文本数据,并计算句子之间的相似度。 需要注意的是,因为语义判断是一个相对主观的过程,所以不同的模型和算法可能会有不同的结果。另外,如果使用基于预训练模型的方法,句子中的单词必须在训练模型的词汇表中才能得到有效的词向量表示。 总结起来,Python可以利用词向量和不同的库来判断句子之间的语义相似度。这些工具可以帮助我们更好地理解和比较文本数据,从而应用到各种自然语言处理任务中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值