【问题标题】:Check the list and split the sentence in python检查列表并在python中拆分句子
【发布时间】:2018-01-02 10:43:02
【问题描述】:

我有一个清单如下。

mylist = ['test copy', 'test project', 'test', 'project']

我想看看我的句子是否包含上述mylistelements,并从第一个匹配中拆分句子并获取它的第一部分。

例如:

mystring1 = 'it was a nice test project and I enjoyed it a lot'

输出应该是:it was a nice

mystring2 = 'the example test was difficult'

输出应该是:the example

我目前的代码如下。

for sentence in L:
    if mylist in sentence:
        splits = sentence.split(mylist)
        sentence= splits[0]

但是,我收到一条错误消息,提示 TypeError: 'in <string>' requires string as left operand, not list。有没有办法解决这个问题?

【问题讨论】:

  • 这里的L是什么?
  • 您在寻找if sentence in mylist?..
  • 您可能在 mylist 中而不是句子中循环,您可以根据列表中的每个单词拆分整个句子。您还将结果分配给新变量。
  • @Sayse:我认为这句话是一个示例输入。

标签: python string list split


【解决方案1】:

您需要另一个for 循环来遍历mylist 中的每个字符串。

mylist = ['test copy', 'test project', 'test', 'project']
mystring1 = 'it was a nice test project and I enjoyed it a lot'
mystring2 = 'the example test was difficult'

L = [mystring1, mystring2]
for sentence in L:
    for word in mylist:
        if word in sentence:
            splits = sentence.split(word)
            sentence= splits[0]
            print(sentence)
# it was a nice 
# the example

【讨论】:

  • 您的答案中缺少 for sentence in L:。非常感谢:)
【解决方案2】:

可能最有效的方法是首先构建一个正则表达式,同时测试所有字符串:

import re

split_regex = re.compile('|'.join(re.escape(s) for s in mylist))

for sentence in L:
    first_part = split_regex.split(sentence, 1)[0]

这会产生:

>>> split_regex.split(mystring1, 1)[0]
'it was a nice '
>>> mystring2 = 'the example test was difficult'
>>> split_regex.split(mystring2, 1)[0]
'the example '

如果可能的字符串数量很大,则正则表达式通常可以胜过单独搜索每个字符串。

你可能还想.strip()这个字符串(去掉字符串前后的空格):

import re

split_regex = re.compile('|'.join(re.escape(s) for s in mylist))

for sentence in L:
    first_part = split_regex.split(sentence, 1)[0].strip()

【讨论】:

  • 非常感谢。非常有用:)
【解决方案3】:
mylist = ['test copy', 'test project', 'test', 'project']
L = ['it was a nice test project and I enjoyed it a lot','a test copy']
for sentence in L:
    for x in mylist:
        if x in sentence:
            splits = sentence.split(x)
            sentence= splits[0]
            print(sentence)

错误表明您正在尝试检查句子中的列表。所以你必须迭代列表的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2012-04-04
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多