简体   繁体   English

Python 中是否有办法以不区分大小写的方式比较变量名和文件名?

[英]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 (例如FooFOOfOo )。 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.pdfFOO.pdfFOo.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.

相关问题 在 Python 中生成随机文件名的最佳方法 - Best way to generate random file names in Python Python中的变量名称有效吗? - Are variable names in Python valid file names? 如何在Python for循环中创建变量名? locals()函数是最好的方法吗? - How are variable names created in a Python for loop? Is the locals() function the best way? Django模型名称不区分大小写,对吗? - Django model names are case insensitive, right? 有没有什么有效的方法可以在 python 中按顺序更改文件名来保存变量? - Is there any efficient way to save variables with changing file names sequentially in python? 有没有办法让rfind()不区分大小写? - Is there a way to make rfind() case insensitive? 有没有办法使用一串变量名作为 function 的输入? - Is there a way to use a string of variable names as input to a function? 有没有办法在 Pyomo 中获取包含变量名的列表? - Is there a way to get a list with variable names in Pyomo? 在 Python 中使用 Selenium 搜索不区分大小写的文本的最佳方法是什么? - What is the best way to search case insensitive text using Selenium in Python? 有没有办法在循环中通过更改名称来编辑变量? - Is there a way to edit a variable with changing names in a loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM