中文分词模拟器

题目描述

给定一个连续不包含空格的字符串,该字符串仅包含英文小写字母及英文标点符号(逗号、分号、句号),同时给定词库,对该字符串进行精确分词。

说明:

精确分词:字符串分词后,不会出现重叠。即"ilovechina",不同词库可分割为"i,love,china","ilove,china",不能分割出现重叠的"i,ilove,china",i 出现重叠

标点符号不成词,仅用于断句

词库:根据外部知识库统计出来的常用词汇例:dictionary = ["i", "love", "china", "lovechina", "ilove"]

分词原则:采用分词顺序优先且最长匹配原则

"ilovechina",假设分词结果 [i,ilove,lo,love,ch,china,lovechina],则输出 [ilove,china]

错误输出:[i,lovechina],原因:"ilove" > 优先于 "lovechina" 成词

错误输出:[i,love,china],原因:"ilove" > "i"遵循最长匹配原则

输入描述

第一行输入待分词语句 "ilovechina"

字符串长度限制:0 < length < 256

第二行输入中文词库 "i,love,china,ch,na,ve,lo,this,is,this,word"

词库长度限制:1 < length < 100000

输出描述

按顺序输出分词结果 "i,love,china"

用例1

输入

ilovechina

i,love,china,ch,na,ve,lo,this,is,the,word

输出

i,love,china

用例2

输入

iat

i,love,china,ch,na,ve,lo,this,is,the,word,beauti,tiful,ful

输出

i,a,t

说明

单个字母,

不在词库中且不成词则输出单个字母

用例3

输入

ilovechina,thewordisbeautiful

i,love,china,ch,na,ve,lo,this,is,the,word,beauti,tiful,ful

输出

i,love,china,the,word,is,beauti,ful

说明

标点符号为英文标点符号

python 复制代码
import re
old_sentences =list(re.split(r'[,.;]',input()))
words = list(re.split(r'[,.;]',input()))
#后续测试发现sentences中可能因为再末尾存在(逗号,分号,句号)导致有空字符串
sentences = [sentence for sentence in old_sentences if sentence!='']
words = set(words)
def match():
    results=[]
    while len(sentences)>0:
        sentence = sentences.pop(0)
        l = len(sentence) #
        while l>0:
            temp = sentence[:l]#因为要优先匹配长的
            if temp in words:#是否存在该单词
                results.append(temp)
                words.remove(temp) #如果每个单词只能用一次的话就得移除,经过测试发现必须去除

                #如果字串词汇只是句子的部分,则剩余部分还要继续
                if l<len(sentence):
                    sentences.insert(0,sentence[l:])
                break
            l-=1

        if l==0:#没找到就输出单个字母
            results.append(sentence[0])
            if len(sentence)>1:
                sentences.insert(0,sentence[1:])

    return  ','.join(results)
print(match())
相关推荐
小白学大数据6 分钟前
Python爬虫中time.sleep()与动态加载的配合使用
爬虫·python·scrapy·数据分析
沐雨潇竹9 分钟前
使用定时器监视当前PID 如果当前程序关闭 UI_Core.exe 也随之自动关闭实现方法
开发语言·qt·ui
小饕14 分钟前
LangChain构建大模型应用之问答系统(五)
人工智能·python·langchain
大锦终16 分钟前
【C++】红黑树
c语言·开发语言·数据结构·c++
David Bates28 分钟前
代码随想录第41天:图论2(岛屿系列)
python·算法·图论
司小豆36 分钟前
视觉-语言基础模型作为高效的机器人模仿学习范式
人工智能·算法·机器人
是代码侠呀41 分钟前
让Promise飞,让github star 飞
python·开源·github·github star·github 加星
咛辉1 小时前
什么是RDD.RDD的创建方式
开发语言
阿月浑子20211 小时前
[C#]Task.Run()和Task.Factory.StartNew()对比(腾讯元宝)
开发语言·c#
伊织code1 小时前
PyTorch API 10 - benchmark、data、批处理、命名张量
pytorch·python·ai·api·-·10