[英]Find exact item of list in a string
I have a problem of false negative during a loop in python. 我在python循环期间遇到假阴性的问题。
That's my list: 那是我的清单:
l = ['modello', 'modello1', 'modello_old', 'new_modello']
and that's a string: 那是一个字符串:
db = '/home/user/modello1.sqlite'
What I want to do is to filter the db
string and to output the element of the list that appear in the string. 我想做的是过滤
db
字符串并输出出现在字符串中的列表元素。
So the result should be only modello1
. 因此,结果应仅为
modello1
。
This is my loop: 这是我的循环:
for i in l:
if i in db:
print i
but the result is not what I would like to obtain: 但结果不是我想要获得的:
modello
modello1
how can I match the exact word? 如何匹配确切的单词?
EDIT : the problem could be that db
is OS dependent so /
could be transformed in \\
. 编辑 :问题可能是
db
依赖于操作系统,所以/
可以在\\
进行转换。
EDIT2 : with @Karoly-Horvath solution: EDIT2 :使用@ Karoly-Horvath解决方案:
transform the db in a list: 转换列表中的数据库:
db = [os.path.basename(db).replace('.sqlite', '')]
loop the element of db
in the whole list: 在整个列表中循环
db
的元素:
for i in db:
if i in l:
print i
Use a regular expression or string functions to extract the relevant part: 使用正则表达式或字符串函数提取相关部分:
m = os.path.basename(db).replace('.sqlite', '') # 'modello1'
or (this was the original answer, only works for unix paths) 或(这是原始答案,仅适用于Unix路径)
m = db.split('/')[-1].replace('.sqlite', '') # 'modello1'
Now you can check for an exact match: 现在您可以检查完全匹配:
m in l # True
If you want to check against the filename without the extension, use os.path.basename
and os.path.splitext
: 如果要检查不带扩展名的文件名,请使用
os.path.basename
和os.path.splitext
:
>>> from os import path
>>> s = '/home/user/modello1.sqlite'
>>> path.basename(s)
>>> 'modello1.sqlite'
>>> path.splitext(path.basename(s))
('modello1', '.sqlite')
>>> filename = path.splitext(path.basename(s))[0]
>>> filename
'modello1'
Using the filename: 使用文件名:
>>> possibles = ['modello', 'modello1', 'modello_old', 'new_modello']
>>> for possible in possibles:
... if possible in filename:
... print possible, 'in', filename
modello in modello1
modello1 in modello1
If you just want to check whether any of the possibilities match: 如果您只想检查是否有任何可能性匹配:
>>> if any(possible in filename for possible in possibles):
... print filename
modello1
I think I understand now that OP would want an exact match: 我想我现在知道OP想要一个完全匹配的东西:
>>> if filename in possibles:
... print filename
modello1
This won't match modello
. 这与
modello
不匹配。
import os
db_basename = os.path.basename(db)
db_basename = os.path.splitext(db_basename)[0] # remove extension
use os
to get file name 使用
os
获取文件名
How about this 这个怎么样
for i in l:
if '/'+i+'.' in db:
print i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.