中文分词模拟器

题目描述

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

说明:

精确分词:字符串分词后,不会出现重叠。即"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())
相关推荐
Hello:CodeWorld26 分钟前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
kaikaile199538 分钟前
数字全息图处理系统(C# 实现)
开发语言·c#
xsc6996751 小时前
从零搭建大模型与智能体平台 - 完整技术详解
python
8Qi82 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
秋92 小时前
Go语言(Golang)开发工程师全景解析:岗位职责·语言优势与使用场景·各城市薪资·发展前景·高考志愿填报(2026版)
开发语言·golang·高考
无风听海2 小时前
多租户系统中的 OIDC:Discovery 端点与联合登录的深度实践
后端·python·flask
CTA终结者3 小时前
期货量化主力换月程序怎么移仓:天勤 underlying_symbol 与任务切换
python·区块链
huangdong_3 小时前
1688商品图片采集技术解析:登录态处理与SKU图自动分类
开发语言
马士兵教育3 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
youngerwang3 小时前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片