我正在使用 textblob 来解析英文文本。这是单词列表。
['Get', 'coffee', 'and', 'water', 'here']
我想在名为 list1 的新列表中获取项目“Get”之后的所有单词。
我想在名为 list2 的新列表中获取“Get”和“here”之间的所有单词。
最好的方法是什么?是否有任何预构建的函数可以执行此操作,因为我想保持脚本干净简单。
任何建议都将受到高度赞赏。
我尝试使用这些函数,但它们不起作用,返回任何空列表。
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def find_between_r( s, first, last ):
try:
start = s.rindex( first ) + len( first )
end = s.rindex( last, start )
return s[start:end]
except ValueError:
return ""
您可以通过查找单词的索引并使用切片来做到这一点:
try:
get_index = l.index('Get')
here_index = l.index('here')
except IndexError:
raise ValueError("Get or here is missing")
without_get = l[get_index + 1:]
without_both = l[get_index + 1:here_index]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)