文本格式为:
资源¥https://kdocs.cn/l/crzS58nUMuN2
每一行文字与链接用¥分割
import json
# 定义文本文件内容到JSON格式的转换函数
def convert_line_to_json(line):
parts = line.strip().split('¥')
if len(parts) == 2:
taskname, shareurl = parts
# 根据给定的示例JSON结构填充字段
task = {
"savepath": "/短剧资源分享/4.20更新",
"pattern": ".*",
"replace": "",
"taskname": taskname,
"shareurl": shareurl
}
return json.dumps(task, ensure_ascii=False)
else:
# 如果行不符合预期格式,则不进行转换
return None
# 读取文本文件并转换为JSON格式
def text_to_json(text_filename, json_filename):
try:
with open(text_filename, 'r', encoding='utf-8') as file:
lines = file.readlines()
# 转换每一行并保存到JSON文件
json_data = [convert_line_to_json(line) for line in lines if line.strip() and '¥' in line]
with open(json_filename, 'w', encoding='utf-8') as json_file:
for data in json_data:
if data: # 确保数据不为None
json_file.write(data + '\n')
except FileNotFoundError as e:
print(f"Error: {e}")
# 使用示例
text_filename = r'txt文件的目录' # 使用原始字符串
json_filename = r'输出output.json目录' # 使用原始字符串
text_to_json(text_filename, json_filename)
文本格式为:
资源https://kdocs.cn/l/crzS58nUMuN2
识别https
import json
# 定义一个函数来解析文本行
def parse_line(line):
# 假设链接总是在行的最后
link_start_index = line.rfind('https')
link = line[link_start_index:].strip()
# 提取剧集名称
name = line[:link_start_index].strip()
return {
"name": name,
"url": link
}
# 读取并解析文件
data = []
with open('代码目录下txt文件', 'r', encoding='utf-8') as file:
for line in file:
if line.strip(): # 跳过空行
data.append(parse_line(line))
# 转换为 JSON 格式
json_data = {"data": data}
# 将 JSON 数据写入到新的文件中
with open('share-data.json', 'w', encoding='utf-8') as json_file:
json.dump(json_data, json_file, ensure_ascii=False, indent=2)
print('转换完成,JSON 数据已写入到 share-data.json 文件中。')
a是追加,w是替换