首页 > 解决方案 > 提取特殊字符正则表达式中的单词

问题描述

我有这样的字符串{'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)'")

标签: pythonregex

解决方案


试试这个正则表达式:

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'

使用此方法将允许您检索字典中其他键的值,而无需创建一整套正则表达式。


推荐阅读