You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python不借助json模块从LD+JSON脚本中提取作者姓名和URL

实现方案

针对你不想使用json模块的需求,这里提供两种简单可直接运行的实现方式:


方法1:正则表达式提取(代码最简洁)

直接通过正则定位author字段下的对应值,匹配逻辑精准:

import re

# data为你存储原始内容的变量
# 提取作者名称
author_name = re.search(r'"author":\{.*?"name":"(.*?)"', data).group(1)
# 提取作者URL
author_url = re.search(r'"author":\{.*?"url":"(.*?)"', data).group(1)

print("作者名称:", author_name)
print("作者URL:", author_url)

运行输出结果:

作者名称: James S. Fisher
作者URL: https://medium.com/@jamessfisher

方法2:纯字符串切割实现(无任何模块依赖)

如果连re模块都不想引入,完全用Python基础字符串操作也可以实现:

# 定位author对象的内容起止位置
author_start_idx = data.find('"author":{') + len('"author":{')
author_end_idx = data.find('}', author_start_idx)
# 截取author内部的字段内容
author_part = data[author_start_idx:author_end_idx]

# 切割提取name值
name_start = author_part.find('"name":"') + len('"name":"')
name_end = author_part.find('"', name_start)
author_name = author_part[name_start:name_end]

# 切割提取url值
url_start = author_part.find('"url":"') + len('"url":"')
url_end = author_part.find('"', url_start)
author_url = author_part[url_start:url_end]

print("作者名称:", author_name)
print("作者URL:", author_url)

注:以上两种方案都是针对你给出的当前数据结构设计,若后续数据结构发生大幅调整可对应修改匹配规则即可。


内容的提问来源于stack exchange,提问作者Qasim0787

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 20:06:01