根据数组中声明的词组拆分句子

时间:2019-01-09 12:17:03

标签: python-3.x

我已经在数组中声明了一些单词并在其上循环,以便如果输入句子中存在该特定单词,则应将其与该单词相应地拆分。

arr_utility = [' my names',
   'my name is ',
   'name ',
   ' names ']



if any(c in str for c in arr_utility):
      print('\nUtility Identified')
      res = str.split(arr_utility[c])
      print(res[1])
else:
      print('No Utility Found')

输入:您好,我叫rahul 输出:rahul

我发现输入中存在该单词,但没有拆分

2 个答案:

答案 0 :(得分:0)

我将其编码如下:

string = "Hello my name is rahul"
arr_utility = [' my names',
   'my name is ',
   'name ',
   ' names ']

for substring in arr_utility:
    if substring in string:
        res = string.split(substring)
        print(res[1])
        break
else:
    print('No Utility Found')

答案 1 :(得分:0)

使用单词边界搜索干草堆字符串中的确切单词 ("Hello my name is rahul")


要创建简单的单词边界,可以使用re.search()

# this will output None
>>> re.search(r'\b{}\b'.format(' my names'), 'Hello my name is rahul')
    None

# this will match uniquely
>>> a = re.search(r'\b{}\b'.format('my name is '), 'Hello my name is rahul')
>>> print (a)
<_sre.SRE_Match object; span=(6, 17), match='my name is '>

所以您只需要从比赛中获得第一个索引即可。


完整的示例:

import re

str = "Hello my name is rahul"
arr_utility = [' my names',
   'my name is ',
   'name ',
   ' names ']

res = [str.split(word)[1] for word in arr_utility if re.search(r'\b{}\b'.format(word), str) is not None]

for outer_list in res:
    for inner_list in outer_list:
        print(inner_list[1])