在Python中使用交集查找多于1个单词

2024-09-27 00:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用以下方法查找一个或多个单词是否在字符串中:

stopwords=set(["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"])
Going = stopwords.intersection(set(testtext[0].split()))

我的问题是,如果字符串有Standard To Slow,那么交集似乎只拾取StandardSlow-我想要Standard To Slow。你知道吗

还有什么我可以改进的吗?你知道吗

为了更清楚地解释我需要什么结果,我将使用以下示例:

我有一份要去的地方的清单

["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"]

我想找出哪些在我的字符串中,例如:

2:20 - H Brown & Son Recycling Maiden Hurdle (Class4) �4,094 Good 2m3f207y

这将返回“好”,因为这是匹配

2:20 - H Brown & Son Recycling Maiden Hurdle (Class4) �4,094 Good to Soft 2m3f207y

这将返回“好到软”,因为这是匹配,而不是“软”


Tags: to字符串standardsoftfastgoodslowset
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:14

交集只能找到匹配的元素。以下是您要比较的列表:

["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"]

testtext[0].split() == ["Standard", "to", "Slow"]

如果只希望它与testtext[0]中的内容匹配,则不应使用split()来创建列表:

Going = stopwords.intersection({testtext[0]})

相关问题 更多 >

    热门问题