Вы можете использовать re.sub для замены всего, что соответствует одной или нескольким символам новой строки (\n
), пробелом в нужных строках:
re.sub(r'\n+', ' ', str)
Если вам необходимо заменить возврат каретки (\r
)), а также переводы строк, вы можете использовать:
re.sub(r'[\r\n]+', ' ', str)
Вот как ваш код изменится:
import re
...
beschreibung_container = container.find_all("pre", {"class":"is24qa-objektbeschreibung text-content short-text"}) or ""
beschreibung = beschreibung_container[0].get_text().strip() if beschreibung_container else ""
ausstattung_container = container.find_all("pre", {"class":"is24qa-ausstattung text-content short-text"}) or ""
ausstattung = ausstattung_container[0].get_text().strip() if ausstattung_container else ""
lage_container = container.find_all("pre", {"class":"is24qa-lage text-content short-text"}) or ""
lage = lage_container[0].get_text().strip() if lage_container else ""
except:
print("Es gab einen Fehler")
f.write(objektid + "##" + titel + "##" + adresse + "##" + criteria.replace(" ", ";") + "##" + preis.replace(" ", ";") + "##" + energie.replace(" ", ";") + "##" + re.sub(r'\n+', ' ', beschreibung) + "##" + re.sub(r'\n+', ' ', ausstattung) + "##" + re.sub(r'\n+', ' ', lage) + "\n")
...