2011-07-31 37 views
0

我尝试使用下面的代码:有麻烦把字符串到一个列表(错误消息)

for x in story: 
    var1 = str(x) 
    var1 = var1.replace("<p>", "\n") 
    var1 = var1.replace("</p>", "") 
    story[x] = var1 

要删除的段落标记,并插入一个换行符,然后将它们重新插入变量。这些字符串如下:

Panera Bread (NASDAQ: <a class="ticker" href="/stock/pnra#NASDAQ">PNRA</a>) is down 6 percent today over expectations of food inflation of 4.5% in Q3 and 5% for Q4. In addition, Panera Will Raise Menu Prices in Q4. 

PNRA recently posted second quarter 2011 earnings of $1.18 per share. Reported earnings also outpaced the prior-year quarter earnings of 85 cents per share. 

But shares were also lower ahead of the opening bell after the company reported weaker-than-expected same-store sales figures for its recent quarter late Tuesday. Its profit of $1.18 a share topped analysts' consensus call by a penny. 

For the twenty-six weeks ended June 28, 2011, net income was $68 million, or $2.27 per diluted share. These results compare to net income of $53 million, or $1.67 per diluted share, for the twenty-six weeks ended June 29, 2010, and represent a 36% year-over-year increase in diluted earnings per share. 

我得到的错误信息是:

Traceback (most recent call last): 
    File "C:\Python27\Sample Programs\Get Stuff from Pages\Pages and Stuff 0.1.py", line 34, in <module> 
    story[x] = var1 
TypeError: list indices must be integers, not Tag 
+1

@tiz答案是正确的,你可能需要编辑和发布你的完整代码,因为你可能会覆盖一些重要的东西,我敢打赌'str' – BrainStorm

回答

2

for循环迭代替代列表story的元素变成x变量,而[]列表指令需要元素索引。这会导致错误。

l = ['a','b'] 
print l[0] 
print l['a'] // type error 

编辑:我错过了故事并没有包含字符串。这种变化可以做的工作:

story = [str(x).replace("<p>","\n").replace("<\p>","") for x in story] 

注意:现在story组成的字符串,而不是标签。

+0

Traceback(最近一次调用最后一次): 文件“C:\ Python27 \ Sample Programs \ Get Pages from Pages and Stuff 0.1.py”,第30行,在 story = [x.replace(“

”, “\ n”)。替换(“

”,“”)为故事中的x] TypeError:'NoneType'对象不可调用 这就是我在做这件事时得到的结果 –

+0

它的工作,但现在我可以' t连接或连接列表中的所有unicode字符串 - 它给我错误。任何想法如何做到这一点? –

+0

@Andrew,我无法想象任何理由...我只能建议创建新问题并发布更详细的代码。 –

0

你可能要追加的项目清单:

story.append(var1) 
+0

这非常缓慢并且冻结了我的系统。 –