我正在尝试将一个字符串转换为一个列表,我想在换行符处拆分它。
html div 中的字符串如下所示:
[<div class="address-lg w-brk-ln-1 ">\r\n \r\n 1010\r\n \r\n \r\n Wien, 01. Bezirk, Innere Stadt\r\n </div>]
[<div class="address-lg w-brk-ln-1 ">\r\n \r\n 1010\r\n \r\n \r\n Wien, 01. Bezirk, Innere Stadt\r\n </div>]
[<div class="address-lg w-brk-ln-1 ">\r\n \r\n Franz-Josefs-Kai 31,\r\n \r\n 1010\r\n \r\n \r\n Wien, 01. Bezirk, Innere Stadt\r\n </div>]
[<div class="address-lg w-brk-ln-1 ">\r\n \r\n 1010\r\n \r\n \r\n Wien, 01. Bezirk, Innere Stadt\r\n </div>]
...
结果我想要的是一个列表:
[Wien, 01. Bezirk, Innere Stadt, 1010, ]
[Wien, 01. Bezirk, Innere Stadt, 1010, ]
[Wien, 01. Bezirk, Innere Stadt, 1010, Franz-Josefs-Kai 31]
[Wien, 01. Bezirk, Innere Stadt, 1010, ]
...
到目前为止,我尝试解决它的方法是这样的:
address = result.select('div.bottom-content div.address-lg.w-brk-ln-1')[0].get_text().strip().replace("\r\n","").split()
address2 = list(reversed(address))
但我得到的总是:
[u'Stadt', u'Innere', u'Bezirk,', u'01.', u'Wien,', u'1010']
[u'Stadt', u'Innere', u'Bezirk,', u'01.', u'Wien,', u'1010']
[u'Stadt', u'Innere', u'Bezirk,', u'01.', u'Wien,', u'1010', u'Sch\xf6nlaterngasse,']
因为它是 unicode,我认为需要 .encode() 它,但我也需要在正确的位置拆分它。
最佳答案
看起来您正在按空格分隔,但您应该按逗号分隔:split(",")
。如果这样做,您可能需要修剪结果,因为它们可能包含大量尾随空格。
但由于您没有指定任何编程语言,这只是一个猜测。
关于html - 将字符串从 html 转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44584715/