在网站中的两个字符串的子字符串之间提取

时间:2016-12-29 21:05:36

标签: python regex substring

我有this site。我想提取出现在文章标题下面的符号(EXAS,ESNT,ENZ,CENT,AEE)。我是一个初学者,所以我尝试了一种相反的反pythonic方法:

import requests
link="https://www.zacks.com/commentary/99386/new-strong-buy-stocks-for-december-29th"
fetch_data = requests.get(link)
content = str((fetch_data.content))
# I know that in the source code the symbols appear between "tickers" and "publish_date" therefore:
tickers= "tickers :"
pd = "publish_date :"
Z= ("%s(.*)%s" % (tickers,pd))
result = re.search(Z, content)
print (result)
# Just printing out the substring between tickers and pd
Output: <_sre.SRE_Match object; span=(95142, 95213), match="tickers : [\\'EXAS\\',\\'ESNT\\',\\'ENZ\\',\\'CEN>

如何打印出符号?此外,最后一个符号'CEN'应打印为'CENT',并且'AEE'符号也缺失。这将是理想的

Symbols: EXAS, ESNT, ENZ, CENT, AEE

或者至少:

"tickers : [\\'EXAS\\',\\'ESNT\\',\\'ENZ\\',\\'CENT\\',\\'AEE\\]

1 个答案:

答案 0 :(得分:1)

您可以访问第一组并清理它:

>>> tickers = result.groups()[0]
>>> re.findall(r'\[.*?\]', tickers)[0].split("\\'")[1::2]
['EXAS', 'ESNT', 'ENZ', 'CENT', 'AEE']