我正在尝试在两个关键字之间搜索文字。到目前为止,我的解决方案是使用split()
将字符串更改为列表。它有效,但我想知道是否有更有效/优雅的方式来实现这一目标。以下是我的代码:
words = "Your meeting with Dr Green at 8pm"
list_words = words.split()
before = "with"
after = "at"
title = list_words[list_words.index(before) + 1]
name = list_words[list_words.index(after) - 1]
if title != name:
var = title + " " + name
print(var)
else:
print(title)
结果:
>>> Dr Green
我更喜欢可配置的解决方案,因为我搜索的文字可以是动态的,因此格林博士可以用4个字或1个字的名称替换。
答案 0 :(得分:3)
听起来像正则表达式的工作。这使用模式(?:with)(.*?)(?:at)
来查找'和'''',并且懒洋洋地匹配中间的任何内容。
import re
words = 'Your meeting with Dr Green at 8pm'
start = 'with'
end = 'at'
pattern = r'(?:{})(.*?)(?:{})'.format(start, end)
match = re.search(pattern, words).group(1).strip()
print(match)
输出;
Dr Green
请注意,正则表达式确实匹配Dr Green
两侧的空格,我包含了一个简单的match.strip()
来删除尾随空格。
答案 1 :(得分:0)
使用RE
import re
words = "Your meeting with Dr Green at 8pm"
before = "Dr"
after = "at"
result = re.search('%s(.*)%s' % (before, after), words).group(1)
print before + result
输出:
Dr Green
答案 2 :(得分:0)
如何在开始和结束时切割列表,然后将其拆分?
words = "Your meeting with Dr Jebediah Caruseum Green at 8pm"
start = "with"
end = "at"
list_of_stuff = words[words.index(start):words.index(end)].replace(start, '', 1).split()
list_of_stuff
['Dr', 'Jebediah', 'Caruseum', 'Green']
您可以使用列表执行任何您喜欢的操作。例如,我会解析这样的标题:
list_of_titles = ['Dr', 'Sr', 'GrandMaster', 'Pleb']
try:
title = [i for i in list_of_stuff if i in list_of_titles][0]
except IndexError:
#title not found, skipping
title = ''
name = ' '.join([x for x in list_of_stuff if x != title])
print(title, name)