Files
my-daily/订阅源/generate_opml.py
T

78 lines
2.4 KiB
Python

import os
import xml.etree.ElementTree as ET
from xml.dom import minidom
base_dir = os.path.dirname(os.path.abspath(__file__))
input_path = os.path.join(base_dir, 'rss_feeds_merged.txt')
output_path = os.path.join(base_dir, 'rss_feeds_merged.opml')
def parse_merged(filepath):
categories = {}
current_category = None
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
if line.startswith('# 英文'):
current_category = '英文军事源'
categories[current_category] = []
continue
if line.startswith('# 中文'):
current_category = '中文微信公众号源'
categories[current_category] = []
continue
if line.startswith('#'):
continue
if '|' in line and current_category:
name, url = line.split('|', 1)
categories[current_category].append((name.strip(), url.strip()))
return categories
def build_opml(categories):
opml = ET.Element('opml', version='2.0')
head = ET.SubElement(opml, 'head')
ET.SubElement(head, 'title').text = '军事科技RSS订阅源'
ET.SubElement(head, 'dateCreated').text = 'Mon, 29 May 2026 12:00:00 +0800'
body = ET.SubElement(opml, 'body')
for cat_name, feeds in categories.items():
cat_outline = ET.SubElement(body, 'outline', text=cat_name, title=cat_name)
for name, url in feeds:
ET.SubElement(
cat_outline,
'outline',
text=name,
title=name,
type='rss',
xmlUrl=url,
)
raw_xml = ET.tostring(opml, encoding='unicode')
dom = minidom.parseString(raw_xml)
return dom.toprettyxml(indent=' ', encoding='UTF-8').decode('utf-8')
def main():
categories = parse_merged(input_path)
xml_str = build_opml(categories)
xml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + xml_str.split('\n', 1)[1]
with open(output_path, 'w', encoding='utf-8') as f:
f.write(xml_str)
total = sum(len(v) for v in categories.values())
for cat, feeds in categories.items():
print(f'{cat}: {len(feeds)} 个')
print(f'总计: {total} 个')
print(f'已写入: {output_path}')
if __name__ == '__main__':
main()