2

我有一个来自股票网络抓取工具的列表,如下所示: [......', 'xlnx>XLNX<', 'yhoo>YHOO<']

我怎样才能得到只有引号的字典?我知道这很简单,但我可以使用一些帮助。谢谢

import urllib
import re

base_url = 'http://www.nasdaq.com/markets/indices/nasdaq-100.aspx'
content = urllib.urlopen(base_url).read()
list = re.findall('http://www.nasdaq.com/symbol/(.*)/a>', content)
print list
4

3 回答 3

2

你有一个列表,而不是字典。此外,您不应该命名您的变量list,因为它是内置的名称。

>>> content
['xlnx>XLNX<', 'yhoo>YHOO<']
>>> tickers = []
>>> for s in content:
...     tickers.append(''.join(i for i in s if i.isupper()))
... 
>>> tickers
['XLNX', 'YHOO']
于 2012-09-08T19:09:02.110 回答
1

您应该使用 HTML 解析器(我总是推荐BeautifulSoup)来解析 HTML,而不是使用正则表达式:

import re, urllib2
from BeautifulSoup import BeautifulSoup

url = 'http://www.nasdaq.com/markets/indices/nasdaq-100.aspx'
soup = BeautifulSoup(urllib2.urlopen(url))

for link in soup.findAll('a', href=re.compile('/symbol/'))[1:]:
  print link.text

输出:

ATVI
ADBE
AKAM
ALXN
ALTR
AMZN
AMGN
APOL
AAPL
AMAT
ADSK
ADP
AVGO
BIDU
BBBY
BIIB
BMC
BRCM
CHRW
CA
CELG
CERN
CHKP
CSCO
CTXS
CTSH
CMCSA
COST
DELL
XRAY
DTV
DLTR
EBAY
ERTS
EXPE
EXPD
ESRX
FFIV
FAST
FISV
FLEX
FOSL
GRMN
GILD
GOOG
GMCR
HSIC
INFY
INTC
INTU
ISRG
KLAC
KFT
LRCX
LINTA
LIFE
LLTC
MRVL
MAT
MXIM
MCHP
MU
MSFT
MNST
MYL
NTAP
NFLX
NUAN
NVDA
NWSA
ORLY
ORCL
PCAR
PAYX
PCLN
PRGO
QCOM
RIMM
ROST
SNDK
STX
SHLD
SIAL
SIRI
SPLS
SBUX
SRCL
SYMC
TXN
VRSN
VRTX
VIAB
VMED
VOD
WCRX
WFM
WYNN
XLNX
YHOO
于 2012-09-08T19:17:31.947 回答
1

像这样的东西:

>>> lis=['xlnx>XLNX<', 'yhoo>YHOO<']
>>> [x[x.index('>')+1:x.index('<')] for x in lis]
['XLNX', 'YHOO']
于 2012-09-08T19:28:49.007 回答