2011-07-31 35 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

這非常緩慢並且凍結了我的系統。 –