[英]Is there a way in Python to compare variable names with file names in a case insensitive way?
I have a function called get_book
which opens requested book by its title
argument.我有一个名为
get_book
的 function ,它通过其title
参数打开请求的书。 Function get_book
can receive title
in any case (eg Foo
, FOO
, fOo
). Function
get_book
在任何情况下都可以接收title
(例如Foo
、 FOO
、 fOo
)。 While this is not a problem in itself, book folder where the function retrieves a book if the title
's are matching, also has book title
s in a mixed case way.虽然这本身不是问题,但如果
title
匹配,function 检索一本书的 book 文件夹也有混合大小写的 book title
。 The database folder is dynamic and continuous to receive new book file names (like eg Foo.pdf
, FOO.pdf
, FOo.pdf
).数据库文件夹是动态且连续的以接收新书文件名(例如
Foo.pdf
、 FOO.pdf
、 FOo.pdf
)。
My question is how can I compare title
s and followingly retrieve requested book without changing file names in the database?我的问题是如何在不更改数据库中文件名的情况下比较
title
并随后检索请求的书? Is there an efficient way to open files without worrying about case matching?有没有一种无需担心大小写匹配的有效方法来打开文件?
my code:我的代码:
def get_book(title):
"""
Retrieves a book by its title. If no such
book exists, the function returns None.
"""
try:
f = default_storage.open(f"books/{title}.pdf")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
Start with an empty lower_to_name
dict.从一个空的
lower_to_name
字典开始。 Probe it like this, for each new title:对于每个新标题,像这样探测它:
title = title.lower() + ".pdf"
title = lower_to_name.get(title, title)
Upon getting FileNotFoundError
for a title, do a single retry using glob to lookup actual filename:获取标题的
FileNotFoundError
后,使用glob进行一次重试以查找实际文件名:
lower_to_name = {name.lower(): name
for name in glob.glob("*.pdf")}
title = lower_to_name.get(title, "no_such_file")
(You may find that os.chdir("books/")
is convenient.) (你可能会发现
os.chdir("books/")
很方便。)
For finding a case-insensitive file name, fnmatch is a good method.对于查找不区分大小写的文件名, fnmatch是一个很好的方法。
This example is almost literally the example in the documentation:这个例子几乎就是文档中的例子:
import fnmatch
import os
title = 'tEst.txt' # Try several combinations of upper and lower case
for file in os.listdir('.'):
if fnmatch.fnmatch(file, title): # They will be all found here
print(file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.