为了账号安全,请及时绑定邮箱和手机立即绑定

如何将列表中的字符串与文本匹配并执行某些操作

如何将列表中的字符串与文本匹配并执行某些操作

牧羊人nacy 2021-06-29 17:59:15
我有关键字列表,让我们在这样的列表中说 6...keywords = ['python', 'c plus plus', 'java', 'javascript', 'c#', 'assembly']并有成千上万这样的句子...... sentence = ['my first python program was a scraping script','i want to learn c plus plus in future','i want to learn java in future too','i love javascript very much','my friend very knowledgeble in c# programming','i heard of assembly but never tried yet']我想要做的是从关键字列表中获取一个关键字,让我们说“python”然后搜索所有句子,如果找到则执行某些操作或否则通过。我尝试过一些东西,但如果我添加更多关键字,那么代码会很长。我在 SO 上进行了搜索,但无法获得我想要完成的任务。有没有更好的方法...提前致谢。这是我尝试过的一些代码keywords = ['python', 'c plus plus', 'java', 'javascript', 'c#', 'assembly']sentence = ['my first python program was a scraping script','i want to learn c plus plus in future','i want to learn java in future too','i love javascript very much','my friend very knowledgeble in c# programming','i heard of assembly but never tried yet']for i in sentence:    if 'python' in i:        lang = 'python'        begining = i.split('python')[-1]        ending = i.split('python')[0]    elif 'c plus plus' in i:        lang = 'c plus plus'        begining = i.split('c plus plus')[-1]        ending = i.split('c plus plus')[0]    elif 'java' in i:        lang = 'java'        begining = i.split('java')[-1]        ending = i.split('java')[0]    elif 'javascript' in i:        lang = 'javascript'        begining = i.split('javascript')[-1]        ending = i.split('javascript')[0]    elif 'c#' in i:        lang = 'c#'        begining = i.split('c#')[-1]        ending = i.split('c#')[0]    elif 'assembly' in i:        lang = 'assembly'        begining = i.split('assembly')[-1]        ending = i.split('assembly')[0]     else:        pass    print lang, begining, ending
查看完整描述

2 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

您可以更有效地进行迭代,如下所示:”


for kw in keywords:

    for sent in sentences:

        if kw in sent:

             lang = kw

             beginning,ending = sent.split(kw,1) ## Force to only split 1 time


查看完整回答
反对 回复 2021-07-06
?
阿晨1998

TA贡献2037条经验 获得超6个赞

languages = [...]

sentences = [...]


for sentence in sentences:

    for language in languages:

        if language in sentence:

            ...


查看完整回答
反对 回复 2021-07-06
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信