AlistSource/urls/main.py

63 lines
2.3 KiB
Python
Raw Normal View History

2024-02-19 21:19:00 +08:00
import os
import urllib.parse
import argparse
2024-02-20 15:34:08 +08:00
import re
2024-02-20 18:49:05 +08:00
import time
2024-02-20 15:34:08 +08:00
def natural_sort_key(s):
"""为了自然排序的辅助函数,将字符串中的数字部分转换成整数"""
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
2024-02-19 21:19:00 +08:00
def generate_urls(file_names, base_url, sub_directory):
"""根据文件名、基础URL和子目录生成URL链接"""
urls = []
2024-02-21 13:48:01 +08:00
# 确保base_url和sub_directory以斜线结尾如果sub_directory不为空
2024-02-19 21:19:00 +08:00
if not base_url.endswith('/'):
base_url += '/'
2024-02-21 13:48:01 +08:00
if sub_directory and not sub_directory.endswith('/'):
2024-02-19 21:19:00 +08:00
sub_directory += '/'
2024-02-20 18:49:05 +08:00
current_timestamp = int(time.time()) # 获取当前时间的时间戳,转换为整数
2024-02-20 15:34:08 +08:00
for name in sorted(file_names, key=natural_sort_key): # 使用自定义排序
2024-02-20 18:49:05 +08:00
file_path = os.path.join('.', name)
file_size_bytes = os.path.getsize(file_path) # 获取文件大小(字节),为整数
2024-02-19 21:19:00 +08:00
# 对文件名进行URL编码
encoded_name = urllib.parse.quote(name)
2024-02-20 18:49:05 +08:00
url = f"{base_url}{sub_directory}{encoded_name}"
urls.append(f"{file_size_bytes}:{current_timestamp}:{url}")
2024-02-19 21:19:00 +08:00
return urls
def save_urls(urls, output_file):
"""将URL链接保存到文本文件中"""
with open(output_file, 'w', encoding='utf-8') as f:
for url in urls:
f.write(url + '\n')
def parse_arguments():
"""解析命令行参数"""
parser = argparse.ArgumentParser(description='Generate URLs from file names.')
2024-02-21 13:48:01 +08:00
parser.add_argument('--dir', type=str, default='', help='Sub-directory for generating file URLs (optional)')
2024-02-19 21:19:00 +08:00
return parser.parse_args()
def main():
# 解析命令行参数
args = parse_arguments()
# 固定的base_url值
base_url = 'https://link.kite.kim/feng'
2024-02-21 13:45:16 +08:00
# 获取当前目录下的所有文件名,排除此脚本文件和隐藏文件
2024-02-19 21:19:00 +08:00
current_script = os.path.basename(__file__)
2024-02-21 13:45:16 +08:00
file_names = [f for f in os.listdir('.') if os.path.isfile(f) and f != current_script and not f.startswith('.')]
2024-02-19 21:19:00 +08:00
# 生成URL链接
urls = generate_urls(file_names, base_url, args.dir)
# 保存URL链接到文本文件
output_file = 'urls.txt'
save_urls(urls, output_file)
print(f"URL链接已保存到{output_file}")
if __name__ == '__main__':
main()