我几乎没有编程经验,所以请原谅我的无知。
我正在尝试解析来自Yahoo!的“关键统计”页面。财务,具体说就是this页面。我一直在玩BeautifulSoup,能够提取我想要的数据,但后来遇到了心理障碍。我希望数据如下所示:
measure[i]: value[i]
.
.
measure[n]: value[n]但是我使用我的脚本得到的结果是:
measure[i]
.
.
measure[n]
value[i]
.
.
value[n]下面是我将两个数据字段连接在一起的尝试,它会抛出一个错误:
measure = soup.findAll('td', {'class':'yfnc_tablehead1'}, width='74%')
value = soup.findAll('td', {'class':'yfnc_tabledata1'})
for incident in measure:
x = incident.contents
for incident2 in value:
y = incident2.contents
data = x + y
print ': '.join(data)此外,我想删除这些值中不需要的字符,但我将阅读re.compile和re.sub文档。
感谢您的任何意见。
发布于 2012-02-15 07:50:47
data = x + y+操作符附加列表,如果您想要耦合列表的相应项,请尝试使用zip()函数:
data = zip(x,y)
for m,v in data:
print m,v另外,
for incident in measure:
x = incident.contents这将在循环的每次迭代中覆盖x,因此最终x只包含分配的最后一个值,而不是所有这些值的聚合。在这里,您可能确实希望像这样使用+运算符:
for incident in measure:
x += incident.contents # x += y is the same as x = x + y当然,另一个循环也是如此。
发布于 2012-02-15 07:53:39
measures = ['1', '2', '3', '4']
values = ['a', 'b', 'c', 'd']
for pair in zip(measures, values):
print ': '.join(pair)
# 1: a
# 2: b
# 3: c
# 4: d关于zip:
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:<built-in function zip>
Namespace: Python builtin
Docstring:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.https://stackoverflow.com/questions/9285922
复制相似问题