提取特殊字符regex中的单词

2024-06-07 00:45:58 发布

您现在位置: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)'")


Tags: 字符串namehttpsapiidurltypecode
1条回答
网友
1楼 · 发布于 2024-06-07 00:45:58

请尝试以下正则表达式:

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'

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

相关问题 更多 >