【问题标题】:music file search in computer in python用python在计算机中搜索音乐文件
【发布时间】:2025-12-16 08:00:02
【问题描述】:

我正在尝试在我的计算机中搜索音乐文件。我尝试了下面给出的代码,但它会在文件名完全相同时给出结果。

import fnmatch
import os
import webbrowser
song = raw_input("enter the song")
to_search = [song + '.mp3']

path = ['G:\\','F:\\','E:\\']
for k in path:
    for root, dirnames, filenames in os.walk(k):
       for extensions in to_search:
        for filename in fnmatch.filter(filenames, extensions):
            matches=(os.path.join(root, filename))
print matches
if not matches:
    print ("no such song is found")
else:
    webbrowser.open(matches)                       #play the song if found

现在我也在尝试搜索这首歌是否有错误的拼写错误,因为如果拼写错误,谷歌也会给出结果。就像我们输入 Michal jackson 而不是 Michael jackson 它会给出结果。所以为此我尝试了以下代码。

import os
import webbrowser
import difflib

song = raw_input("enter the song")
to_search = [song + '.mp3']
path = ['E:\\']
for root, dirnames, filenames in os.walk(path[0]):
    d = difflib.SequenceMatcher(None,filenames, to_search).ratio()
    if d>=0.6:
        print d
        matches=(os.path.join(root,filenames))

webbrowser.open(matches)

但我没有得到结果。谁能告诉我错误是什么或为什么我没有得到。

【问题讨论】:

    标签: python python-2.7 search


    【解决方案1】:

    试试glob 包和类似的东西:

    for file in glob.glob('G:\\*\\*.mp3"):
        print(file)
    

    这可能不是你的全部答案,但我想你可以从这里到达那里。

    【讨论】:

      【解决方案2】:

      SequenceMatcher 中,您将一个包含多个文件名的列表与一个仅包含您要查找的文件名的列表进行比较。因此,不匹配的结果。 请尝试以下操作:

      import os
      import webbrowser
      import difflib
      
      
      song = raw_input("enter the song")
      to_search = song + '.mp3'
      path = ['E:\\']
      for root, dirnames, filenames in os.walk(path[0]):
          for filename in filenames:
              d = difflib.SequenceMatcher(None,filename, to_search).ratio()
              if d>=0.6:
                  matches=(os.path.join(root, filename))
      
      webbrowser.open(matches)
      

      【讨论】:

      • 很高兴,如果这个答案解决了您的问题,请考虑支持/接受它。
      • 我不能这样做,因为我没有足够的声誉这样做。请投票我的问题,以便我可以帮助你:)
      • 嘿 jacques...我想使用 Django rest-framework 制作 youtube API。是否可以这样做。如果可以,我应该如何开始。这将是我的第一个 API工作。
      • 您应该问另一个问题,并更具体地说明您想要实现的目标。我可能不是最适合回答的人,因为我对 google youtube API 了解不多。祝你好运!
      • okkk...你能告诉我优秀的 Python 程序员应该具备哪些知识吗?