2013-10-05 2 views
0

Как я могу конкатенировать строку 27? Я получаю «TypeError: не может конкатенировать объекты« str »и« list ». Это потому, что я использую переменную изменения в списке символов?Python & Excel Concatenate

Это линия я говорю:

ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price 

Ниже rewst моего кода и строки 27.

from openpyxl import Workbook 

import urllib 
import re 

from openpyxl.cell import get_column_letter 

wb = Workbook() 

dest_filename = r'empty_book.xlsx' 

ws = wb.create_sheet() 

ws.title = 'Stocks' 
symbolslist = ["aapl","spy","goog","nflx"] 

i=0 
while i<len(symbolslist): 
    #counts each object as 1 in the list 
    url = "http://finance.yahoo.com/q?s="+symbolslist[i]+"&q1=1" 
    htmlfile = urllib.urlopen(url) 
    htmltext = htmlfile.read() 
    regex = '<span id="yfs_l84_'+symbolslist[i]+'">(.+?)</span>' 
    pattern = re.compile(regex) 
    price = re.findall(pattern,htmltext) 
    print "The price of", symbolslist[i], " is ", price 
    ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price 
    i+=1 


wb.save(filename = dest_filename) 
+0

're.findall()' возвращает список. Он жалуется на 'price', а не на' symbollist'. –

ответ

4

re.findall() всегда возвращает список; возможно, вы хотели, чтобы превратить это в строку:

ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + ','.join(price) 

В качестве альтернативы, печатать только первый элемент:

ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price[0] 

Синтаксический HTML проще с HTML-парсер; BeautifulSoup был бы лучшим инструментом:

import urllib 
from bs4 import BeautifulSoup 

for symbol in symbolslist: 
    url = "http://finance.yahoo.com/q?s={}&q1=1".format(symbol) 
    response = urllib.urlopen(url) 
    soup = BeautifulSoup(response, from_encoding=response.headers.getparam('charset')) 
    price = soup.find('span', id='yfs_l84_' + symbol).text 
    text = "The price of {} is {}".format(symbol, price) 
    print text 
    ws.cell(1,i+1).value = text 

Быстрый демо:

>>> import urllib2 
>>> from bs4 import BeautifulSoup 
>>> symbolslist = ["aapl","spy","goog","nflx"] 
>>> for symbol in symbolslist: 
...  url = "http://finance.yahoo.com/q?s={}&q1=1".format(symbol) 
...  response = urllib.urlopen(url) 
...  soup = BeautifulSoup(response, from_encoding=response.headers.getparam('charset')) 
...  price = soup.find('span', id='yfs_l84_' + symbol).text 
...  text = "The price of {} is {}".format(symbol, price) 
...  print text 
... 
The price of aapl is 483.03 
The price of spy is 168.89 
The price of goog is 872.35 
The price of nflx is 327.26 
+0

Как изменить re.findall() в строку? –

+0

@RobB .: либо с помощью первого элемента, либо путем объединения всех элементов в строку. Я привел вам примеры обоих вариантов. –

+0

Прохладный, спасибо за информацию. –

Смежные вопросы