简体   繁体   English

如何打开最接近指定python文件的文件

[英]how to open a file closest to the file specified python

I am using python and I wand to run a program the will open the file specified by the user. 我使用的是python,并且我想用它来运行一个程序,它将打开用户指定的文件。 But the problem is that, if the user doesn't specify the exact file name, then it will give an error. 但是问题在于,如果用户未指定确切的文件名,那么它将给出错误。 If the user wants to open "99999-file-name.mp3" and he has typed "filename.mp3", then how can the program open the file closest to the one specified? 如果用户要打开“ 99999-file-name.mp3”,并且键入了“ filename.mp3”,那么程序如何打开最接近指定文件的文件?

First get a list of files in the particular folder 首先获取特定文件夹中的文件列表

Then use difflib.get_close_matches like so: 然后像这样使用difflib.get_close_matches

difflib.get_close_matches(user_specified_file, list_of_files)

to find "good" matches. 寻找“好的”比赛。

NB: Consider putting a providing a small cutoff ie 0.1 as suggested by @tobias_k to ensure you do you get a match always as the default cutoff of 0.6 means sometimes nothing will be a "good match" for what the user entered. 注意:请考虑提供一个小的cutoff@tobias_k所建议的0.1,以确保您始终都能获得匹配,因为默认截止值0.6意味着有时对于用户输入的内容而言,没有什么是“好的匹配”。

Similarly if you need to get only one file name also pass in the optional parameter n=1 to get the closest match since if you don't specify it you will get the 3 best matches. 同样,如果只需要获取一个文件名,则还要传入可选参数n=1以获得最接近的匹配项,因为如果不指定它,则将获得3个最佳匹配项。

To answer this question, you need to first define "closest" because in computing this can mean very different things. 要回答这个问题,您需要首先定义“最近”,因为在计算中这可能意味着非常不同的事情。 If you want to compare strings and find the most similar, then one good way of doing that is checking the edit distance. 如果要比较字符串并找到最相似的字符串,那么一种好的方法是检查编辑距离。 There are Python libraries out there for that, ie https://pypi.python.org/pypi/editdistance . 那里有Python库,例如https://pypi.python.org/pypi/editdistance
You give it two strings and it tells you how much you have to change one string to get the other. 您给它两个字符串,它告诉您必须更改一个字符串才能得到另一个字符串。 As per the documentation: 根据文档:

>>> import editdistance
>>> editdistance.eval('banana', 'bahama')
2L

PS. PS。 Can't help but to mention that I think this is a bad idea. 不禁要提到,我认为这是一个坏主意。 If you want to do sth with the file opened and the program starts opening random files, then either you're eventually gonna overwrite a file that is not meant to be overwritten or you try to process a file that can't be processed in your intended way. 如果您想打开文件,然后程序开始打开随机文件,那么您要么将要覆盖一个本不应该被覆盖的文件,要么尝试处理无法在您的文件中处理的文件预期的方式。 I would recommend using a file select box that you can easily use with tKinter for example (even though tKinter is cancer). 我建议使用一个文件选择框,例如,您可以轻松地将其与tKinter一起使用(即使tKinter是癌症)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM