2012-08-25 13 views
7

He intentado analizar letras de canciones del mayor sitio de letras rusas http://amalgama-lab.com y guardar letras (traducidas y originales) en la lista de audio de mi cuenta Vkontakte (tristemente , amalgama no tiene ninguna API)BeautifulSoup .text método devuelve texto sin separadores ( n, r etc)

import urllib 
from BeautifulSoup import BeautifulSoup 
import vkontakte 
vk = vkontakte.API(token=<SECRET_TOKEN>) 
audios = vk.getAudios(count='2') 
#{u'artist': u'The Beatles', u'url': u'http://cs4519.vkontakte.ru/u4665445/audio/4241af71a888.mp3', u'title': u'Yesterday', u'lyrics_id': u'2365986', u'duration': 130, u'aid': 166194990, u'owner_id': 173505924} 
url = 'http://amalgama.mobi/songs/' 
for i in audios: 
    print i['artist'] 
    if i['artist'].startswith('The '): 
     url += i['artist'][4:5] + '/' + i['artist'][4:].replace(' ', '_') + '/'  +i['title'].replace(' ', '_') + '.html' 
    else: 
     url += i['artist'][:1] + '/' + i['artist'].replace(' ', '_') + '/' +i['title'].replace(' ', '_') + '.html' 
    url = url.lower() 
    page = urllib.urlopen(url) 
    soup = BeautifulSoup(page.read(), fromEncoding="utf-8") 
    texts = soup.findAll('ol',) 
    if len(texts) != 0: 
     en = texts[0].text #this! 
     ru = texts[1].text #this! 
     vk.get('audio.edit', aid=i['aid'], oid = i['owner_id'], artist=i['artist'], title = i['title'], text = ru, no_search = 0) 

pero el método .text devuelve cadena y sin ningún separador:

"Ayer, todos mis problemas parecían tan lejos awayNow que parezca como si estuvieran aquí quedarse Oh, creo en el ayer. De repente, no soy la mitad de hombre que solía ser. Hay una sombra que cuelga sobre r meOh, ayer llegó de repente [Estribillo:] ¿Por qué tenía que ir? No sé, ella no diría que dije algo mal, ahora anhelo el ayer. Ayer, el amor fue un juego tan fácil de jugar. Ahora necesito un lugar para esconderme. awayOh, creo en "

Es el principal problema. A continuación, ¿qué mejor manera de ahorrar letras esta manera:

línea de Letras 1 (original)

Letras línea 1 (Traducido)

línea de Letras 2 (Original)

línea de Letras 2 (traducido)

línea Letras 3 (original)

línea Letras 3 (traducido)

...

? Solo obtengo un código desordenado. Gracias

+0

Sírvanse proporcionar un enlace a la página real que se está analizando. – BrenBarn

+0

Ejemplo: http://amalgama.mobi/songs/b/beatles/yesterday.html –

+1

Tenga en cuenta que * no hay * líneas nuevas en el texto de la canción, solo las etiquetas '
', que el OP está eliminando. –

Respuesta

0

Usted puede hacer esto:

soup = BeautifulSoup(html) 
ols = soup.findAll('ol') # for the two languages 

for ol in ols: 
    ps = ol.findAll('p') 
    for p in ps: 
     for item in p.contents: 
      if str(item)!='<br />': 
       print str(item) 
8

Prueba el parámetro separator del método get_text:

from bs4 import BeautifulSoup 
html = '''<p> Hi. This is a simple example.<br>Yet poweful one. <p>''' 
soup = Beautifulsoup(html) 
soup.get_text() 
# Output: u' Hi. This is a simple example.Yet poweful one. ' 
soup.get_text(separator=' ') 
# Output: u' Hi. This is a simple example. Yet poweful one. ' 
Cuestiones relacionadas