简体   繁体   English

如何在 Python 中找到精确字符串匹配?

[英]How to find Exact String Match in Python?

I have list of words and want to check if string contains any of words from a list.我有单词列表,想检查字符串是否包含列表中的任何单词。

The code编码

String : "Business communication is often termed as the lifeblood of business concern justify this statement with an example"  
words = ['Fortnite', 'Digital Games',"Business","Technology","periodic table","med","ments"] 
for s in Q:
    s=re.sub('[^A-Za-z0-9]+'," ",s)

    print(s)
    for k in words:
        if k.lower() in s: 
            print(k)

Results: Business, med结果:商业,医学

Expected Output: Business预期 Output:业务

string = " " + inputString + " "
for word in words:
    if (" " + word + " ") in string:
        print(word)

Adding spaces in condition prevents problems with sub-words like med .在条件中添加空格可以防止像med这样的子词出现问题。 First line allows first and last word to be found.第一行允许找到第一个和最后一个单词。 If you need to deal with commas and periods then additional coding is required.如果您需要处理逗号和句点,则需要额外的编码。

Why not:为什么不:

#!/usr/bin/env python3
words = ['Fortnite', 'Digital Games',"Business","Technology","periodictable","med","ments"]
inputString = "Business communication is often termed as the lifeblood of business concern justify this statement with an example"
for word in words:
    for string in inputString.split(' '):
        if word == string:
            print(word)

It's computationally expensive, but it seems like it will do what you want it to do.它的计算成本很高,但它似乎会做你想做的事。 Your regex string is nowhere near complicated enough to search for the words you want it to search for.您的正则表达式字符串远不够复杂,无法搜索您希望它搜索的单词。

Given words and inputString :给定wordsinputString

words = ['Fortnite', 'Digital Games',"Business","Technology","periodictable","med","ments"]
inputString = "Business communication is often termed as the lifeblood of business concern justify this statement with an example"

you can create sets and take the intersection:您可以创建集合并采取交叉点:

wset = set(words)
inpset = set(inputString.split())
print(wset & inpset)

which prints哪个打印

{'Business'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM