我有一个带有somer版本号的字符串列表。我想在一个段落中找到(确切的)这些字符串列表 实例 products=[“productA v4.1”、“productA v4.1.5”、“productA v4.1.5版本”]
段落=“productA v4.1.5文档的故障排除步骤”
在这种情况下,如果Iam使用如下过滤器
products = ["productA v4.1", "productA v4.1.5", "product A v4.1.5 ver"]
paragraph = "Troubleshooting steps for productA v4.1.5 documents"
def checkIfProdExist(x):
if paragraph.find(x) != -1:
return True
else:
return False
results = filter(checkIfProdExist, products)
print(list(results))
以上代码的输出是 ['ProductaV4.1','ProductaV4.1.5']
如何在段落中仅查找“productA v4.1.5”并获取其索引值
通过对产品列表进行反向排序并从段落中删除第一个匹配的产品实例,解决了我的用例。下面是我如何做的代码。这可能是正确的方法,也可能不是正确的方法,但解决了我的问题。即使产品列表中有n个产品,并且段落中有许多来自产品列表的匹配字符串,它也在工作。感谢您的研究和帮助
听起来您基本上希望匹配的开始和结束要么是段落的结尾,要么是到空格字符的转换(“单词”的结尾,尽管遗憾的是,单词的正则表达式定义排除了像
.
这样的内容,所以您不能使用基于\b
的测试)这里最简单的方法是用空格分割行,然后查看您的字符串是否出现在结果} 上的一些变体):
list
(使用finding a sublist in a ^{如果您也需要索引,或者需要精确的空格匹配,那么它就更复杂了(
.split()
不会保留空格的运行,因此您无法重建索引,如果您对整个字符串进行索引,并且子字符串出现两次,但只有第二次满足您的要求,那么您可能会得到错误的索引)。在这一点上,我可能会使用正则表达式:请注意,如前所述,这不适用于
filter
(如果段落以子字符串开头,则返回0
,即falsy)。您可能会让它在失败时返回None
,在成功时返回tuple
个索引,因此它在布尔值和索引要求较高的情况下都有效,例如(演示海象使用3.8+的乐趣):您希望找到最长的匹配项,因此应首先使用最长字符串开始匹配:
输出:
相关问题 更多 >
编程相关推荐