如何在Python中找到精确的字符串匹配?
我有一个单词列表,想检查字符串是否包含列表中的任何单词 代码如何在Python中找到精确的字符串匹配?,python,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"
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)
结果:商业,医学
预期产出:业务为什么不:
#!/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)
它的计算代价很高,但它似乎可以实现您希望它实现的功能。您的正则表达式字符串远不够复杂,无法搜索您希望它搜索的单词。给定
单词
和输入字符串
:
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'}
string=”“+inputString+“”
用文字表示:
如果字符串中有(“+word+”):
打印(word)
在条件中添加空格可防止子词出现问题,如
med
。第一行允许找到第一个和最后一个单词。如果您需要处理逗号和句点,则需要额外的编码。这是不可复制的。单词列表是单词=['Fortnite'、'Digital Games'、'Business'、'Technology'、'periodic table'、'med'、'med']@Peter您的意思是什么?这一个同时返回Business和med。当我在寻找字符串的精确匹配而不是字符串的子集时,我修改了答案。不,这个也不起作用。Split()拆分字符串中的单词我在单词列表中有一些单词,其中包含两个以上的单词。e、 元素周期表(错误地连接在一起)这里,是任何输入字符串都有元素周期表,我希望程序返回精确匹配的“元素周期表”。不,这个也不起作用。Split()拆分字符串中的单词我在单词列表中有一些单词,其中包含两个以上的单词。e、 g周期表(错误地连接在一起)这里,是任何输入字符串都有周期表,我希望程序返回精确匹配的“周期表”。