如何从文件列表创建电影数据库

0 投票
1 回答
3396 浏览
提问于 2025-04-18 06:36

我家服务器上有很多电影,大约有4000部。这些电影文件的命名格式是 标题 - 副标题 (年份).扩展名。我想创建一个数据库(即使是用Excel也可以),把所有电影的信息都记录下来。这个数据库应该包含几个栏目:标题、副标题(如果有的话)、年份和文件在服务器上的位置(有些电影是按类型或演员放在不同文件夹里的)。目前我有一个bash脚本,它会生成一个文本文件,里面列出了每个硬盘上的文件(每个文件都是对应一个硬盘的列表)。我想知道怎么才能在我的家用服务器上自动创建这样的数据库(我的服务器是运行Debian系统的)。

如果能自动从一些电影数据库的API获取其他电影信息就更好了,但我觉得这可能会很复杂。

1 个回答

1

这个问题比较宽泛,不太适合在这里讨论(这里更像是教程而不是快速的代码问题),不过我可以给你一些策略上的建议:

  • Excel可以打开.csv文件,并把逗号和换行符当作单元格来处理。所以
  • 你需要遍历目录,可能还要递归遍历
  • 扩展路径名——如果你使用像Python这样的高级语言,可以通过标准函数来实现;然后用正则表达式来解析最后一部分
  • 把每个路径的格式化内容存储为列表中的行
  • 把这个列表打印到一个文本文件中,用逗号连接每个元素,用换行符分隔每一行
  • 给这个文件加上.csv的后缀,然后在Excel中打开它

需要注意的是,如果你真的想要一个正规的数据库,Python也是一个不错的选择——SQLite是标准安装的一部分。

祝好运!


更新:哈哈,你在我回答的时候编辑了问题。看起来你需要的一切都在文件名里,但如果你打算使用元数据,这里有个提醒。如果你的文件不是来自同一个来源,提取元数据可能会变得复杂;并不是每种媒体类型都有相同的元数据结构,也不是每个创建文件的应用程序都提供相同的元数据。所以获取元数据的逻辑可能会变得混乱。

你有没有考虑过使用现有的程序来完成这个任务?

最后你提到要把它放到你的网络服务器上;再次提到Python,标准包中也内置了你需要的请求服务器的功能。


最后更新

我对bash不太在行;在这方面我很笨,也不是Python的专家,但你的目标相对简单。我没有测试过这个——可能有一两个拼写错误,可以把它当作大部分可以在Python中使用的伪代码。

# import the standard libraries you'll need
import os # https://docs.python.org/2/library/os.html
import re # https://docs.python.org/2/library/re.html

# this function will walk your directories and output a list of file paths
def getFilePaths(directory):
    file_paths = []
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)
    return file_paths



video_file_paths = getFilePaths("path/to/video/library")
output_to_csv = [];
for video_file in video_file_paths:
    base_path, fname = os.path.split(video_file) 

     """ This is a super simple bit of regex that, provided  your files are all formatted as
     written, will parse out title, subtitle, year and file extension. If your file names
     turn out to have more exceptions than you expect (I'd be shocked if not), you may need
     to make this part more robust, either with much more savvy regex, or else some conditional
     logic—maybe a recursive try... catch loop"""
    reg_ex = re.compile("/^(.*) - (.*) \((.*)\)\.(.*)$/");

    # now apply the compiled regex to each path
    name_components = reg_ex.match(fname);

    """Each output is a row of your CSV file; .join() will join the 4 elements of the regex
    match (assuming, again, that your filenames are as clean as you claim), and then add
    the basepath, so you should be building, in this loop, a list with elements like:
    title, subtitle, year, file_extension, full path"""

    output_to_csv.append("{0},{1}".format(name_components.join(","), base_path));

#create the file, making sure the location is writeable
csv_doc = open("my_video_database.csv", "w");

# now join all the rows with line breaks and write the compiled text to the file
csv_doc.write( ouput_to_csv.join("\n") ); 

#close  your new database
csv_doc.close()

撰写回答