python - 提取特殊字符正则表达式中的单词
问题描述
我有这样的字符串{'id': '00045a8c33174826', 'url': 'https://api.twitter.com/1.1/geo/id/00045a8c33174826.json', 'place_type': 'city', 'name': 'Thanon Nakhon Chai Si', 'full_name': 'Thanon Nakhon Chai Si, Thailand', 'country_code': 'TH', 'country': 'Thailand', 'contained_within': [], 'bounding_box': {'type': 'Polygon', 'coordinates': [[[100.5057265, 13.7741202], [100.5370861, 13.7741202], [100.5370861, 13.800442499999999], [100.5057265, 13.800442499999999]]]}, 'attributes': {}}
我想得到输出:TH
谁能帮我快速做到这一点?我已经尝试过了,但它似乎不正确:
re.search("'country_code': '(\w)'", text)
谢谢你。
更新:我用过
df.str.extract(r"'country_code': '(\w)'")
解决方案
试试这个正则表达式:
r"'country_code': '(.*)'"
该正则表达式将提供以下结果:
>>> import re
>>> regex = re.compile(r"'country_code': '(.*)'")
>>> string = "'country_code': 'TH'"
>>> regex.search(string).group(1)
'TH'
>>>
但是,如果这是 JSON 内容,我建议使用 Python StdLibjson
模块:
>>> import json
>>> string_data = "{...}"
>>> data = json.loads(string_data)
>>> data["country_code"]
'TH'
使用此方法将允许您检索字典中其他键的值,而无需创建一整套正则表达式。
推荐阅读
- php - 在 PHP 中将字符串解码为西里尔符号
- extjs - 在前端计算/转换 id 字段
- django - 允许用户以交互模式上下移动特定主题
- umbraco - 使用 Umbraco 获取特定类型的所有强类型文档
- c# - 如何在类中保存字段的值
- python - 如何在没有键的情况下打印字典的元素?
- vba - 每当下拉列表更改区域中的单元格时,Excel VBA 会自动运行宏
- html - What type of script it is which is begin with a hash sign # among html
- javascript - 开发可配置模板的正确方法是什么?
- wordpress - woocommerce 产品变体选择警报框定制