new-m3u_to_txt.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. import re
  3. from collections import defaultdict
  4. def parse_m3u(m3u_file):
  5. """
  6. 解析M3U文件并将其转换为指定格式的TXT文件
  7. :param m3u_file: M3U文件的路径
  8. """
  9. # 生成输出TXT文件的路径
  10. txt_file = os.path.splitext(m3u_file)[0] + ".txt"
  11. # 读取M3U文件内容
  12. with open(m3u_file, 'r', encoding='utf-8') as f:
  13. lines = f.readlines()
  14. channels = defaultdict(list)
  15. for i in range(len(lines)):
  16. line = lines[i].strip()
  17. if line.startswith('#EXTINF:'):
  18. # 提取分组信息
  19. group_match = re.search(r'group-title="([^"]*)"', line)
  20. group = group_match.group(1) if group_match else "未分组"
  21. # 提取频道名称 - 查找方括号中的内容
  22. name_match = re.search(r'\[([^\]]*)\]\s*(.+)$', line.split(',')[-1])
  23. if name_match:
  24. # 如果找到方括号格式,使用方括号后面的内容作为名称
  25. name = name_match.group(2).strip()
  26. else:
  27. # 如果没有方括号格式,使用逗号后的完整内容
  28. name = line.split(',')[-1].strip()
  29. # 获取URL(假设URL在下一行)
  30. if i + 1 < len(lines):
  31. url = lines[i + 1].strip()
  32. if url and not url.startswith('#'):
  33. channels[group].append((name, url))
  34. # 写入TXT文件
  35. with open(txt_file, 'w', encoding='utf-8') as f:
  36. for group, channel_list in channels.items():
  37. f.write(f"{group},#genre#\n")
  38. for name, url in channel_list:
  39. f.write(f"{name},{url}\n")
  40. f.write("\n") # 在每个分组后添加一个空行
  41. def convert_all_m3u_files():
  42. """
  43. 转换当前目录下的所有M3U文件
  44. """
  45. current_directory = os.getcwd()
  46. for file in os.listdir(current_directory):
  47. if file.endswith(".m3u"):
  48. m3u_path = os.path.join(current_directory, file)
  49. print(f"正在转换: {m3u_path}")
  50. parse_m3u(m3u_path)
  51. if __name__ == "__main__":
  52. convert_all_m3u_files()