如何在Python中找到完全匹配的字符串?

时间:2020-04-28 17:14:15

标签: python

我有单词列表,想检查字符串是否包含列表中的任何单词。

代码

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)

结果:商业,医学

预期产出:商业

3 个答案:

答案 0 :(得分:1)

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

在条件中添加空格可以防止诸如med之类的子词出现问题。第一行允许找到第一个和最后一个单词。如果需要处理逗号和句点,则需要附加编码。

答案 1 :(得分:0)

为什么不呢?

program Project1;

var p : real;

const s=439 ;

begin
     p:=s/100;
     Write(p);
     ReadLn;
end.

它在计算上很昂贵,但似乎可以完成您想要的操作。您的正则表达式字符串非常复杂,不足以搜索您想要它搜索的单词。

答案 2 :(得分:0)

给出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"

您可以创建集合并采用交集:

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

可打印

{'Business'}