Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 提取特殊字符regex中的单词_Python_Regex - Fatal编程技术网

Python 提取特殊字符regex中的单词

Python 提取特殊字符regex中的单词,python,regex,Python,Regex,我有这样的字符串{'id':'00045a8c33174826','url':'https://api.twitter.com/1.1/geo/id/00045a8c33174826.json“,”地点类型“:”城市“,”姓名“:”塔农那鸿柴司“,”全名“:”塔农那鸿柴司,泰国“,”国家代码“:”TH“,”国家“:”泰国“,”包含在“:[],”边界框“:{'type':'Polygon','coordinates':[[100.5057265,13.7741202],[100.5370861,1

我有这样的字符串
{'id':'00045a8c33174826','url':'https://api.twitter.com/1.1/geo/id/00045a8c33174826.json“,”地点类型“:”城市“,”姓名“:”塔农那鸿柴司“,”全名“:”塔农那鸿柴司,泰国“,”国家代码“:”TH“,”国家“:”泰国“,”包含在“:[],”边界框“:{'type':'Polygon','coordinates':[[100.5057265,13.7741202],[100.5370861,13.7741202],[100.5370861,13.80044249999999],[100.5057265,13.800442499999],[attributes':{}

我想得到输出:
TH

有人能帮我快点吗?我已经试过了,但似乎不正确:

re.search("'country_code': '(\w)'", text) 
多谢各位

更新:我用过


df.str.extract(r“'country\u code':'(\w)”)
尝试以下正则表达式:

r"'country_code': '(.*)'"
该正则表达式将提供以下结果:

>>重新导入
>>>regex=re.compile(r“'country_code':'(.*)”
>>>string=“'country_code':'TH'”
>>>regex.search(string.group)(1)
“TH”
>>> 
但是,如果这是JSON内容,我建议使用Python StdLib
JSON
模块:

导入json >>>字符串_data=“{…}” >>>data=json.load(字符串\数据) >>>数据[“国家/地区代码”] “TH”
使用此方法将允许您检索字典中其他键的值,而无需创建一整套正则表达式。

您是否正在尝试解析JSON内容,如果是,是否可以包含完整字符串?@TimBiegeleisen:我已包含完整字符串。谢谢。如果您使用OP提供的整个字符串,您将获取比您想要的更多的内容。您可能希望解决此问题。将字符串设置为OP给定的整个字符串,以查看我所指的内容。除非我缺少某些内容。我认为您希望将
regex
更改为
regex=re.compile(r“'country\u code':”([^']*))
。这将匹配
,后跟任何非单引号的内容,然后后跟单引号
。忘记正则表达式,将其作为JSON加载是更好的方法。Jacob,一个问题是所提供的字符串不是有效的JSON,
。load()
将阻塞它。您需要将
替换为
在将其发送到
.loads()
之前。只需使用
string\u data=“{…}.replace(“”,“\”)
@JeffC即可。我正在尝试将其作为JSON加载。但是,在将其替换为之后”,有一个错误:
JSONDecodeError:Expecting',delimiter
。您能帮我吗?谢谢。@Jason最好是问一个新问题,而不是在其他问题的评论中把它全部整理出来。发布您正在尝试做的事情、您尝试过的事情以及具体的错误消息。如果我看不到,请找人告诉我我一定会帮助你的。