在列表中从BeautifulSoup输出拆分字符串 [英] Split string from BeautifulSoup output in a list
问题描述
我的代码有以下输出
代码: text = soup.get_text()
输出:
Article Title
Some text: Text blurb.
More blurb.
Even more blurb.
Some more blurb.
Second Article Title
Some text: Text blurb.
More blurb.
Even more blurb.
Some more blurb.
接下来,当我执行 test = text.splitlines()
时,输出更改为
Next, when I do test = text.splitlines()
, the output changes to
u'Article Title', u'', u'Some text',u'Text blurb',u'More blurb',u'Even more blurb',u'Some more blurb',, u'', u'', u'', u'', u'',u'Second Article Title', u'', u'Some text:',u'Text blurb',u'More blurb',u'Even more blurb',u'Some more blurb',, u'', u'', u'', u'', u'',
我想用 u'',u'',u'',u'',u''
分割字符串,以便随后分别解析各行.我本来想使用标签,但是它们的结构使它难以使用.
I'd like to split the string using u'', u'', u'', u'', u''
so that I can then individually parse out the lines. I'd have liked to use the tags but their structure makes it difficult to use.
如何执行拆分?我已经尝试过:
How do I perform the split? I have tried:
result = [list(g) for k,g in groupby(test,lambda x:x=="u''") if not k]
print result
和
for item in test:
arr = re.split("u'', u'', u'', u'', u''",item, flags=re.UNICODE)
print arr
但是他们没有给我想要的输出.
but they don't give me the desired output.
推荐答案
如果您查看文字,则希望通过重复的换行符 \ n
从
If you take a look at your text, you want to split by repeated newlines \n
from
text
>> 'Article Title\n\n Some text: Text blurb.\n\nMore blurb.\n\nEven more blurb. \n\nSome more blurb. \n\n\n\n\n\nSecond Article Title\n\nSome text: Text blurb.\n\nMore blurb.\n\nEven more blurb. \n\nSome more blurb. '
然后,您可以仅使用 text.split('\ n \ n \ n \ n \ n')
的定义参数,如果不添加参数,Python会简单地按空格.第一次拆分后,您可以按 \ n \ n
拆分其他元素.
You can then just use define a parameter for text.split('\n\n\n\n\n')
, if you don't add a parameter, Python simply splits by whitespaces. After your first split, you can then split your other elements by \n\n
.
[i.split('\n\n') for i in text.split('\n\n\n\n\n')]
>>[['Article Title',
' Some text: Text blurb.',
'More blurb.',
'Even more blurb. ',
'Some more blurb. '],
['\nSecond Article Title',
'Some text: Text blurb.',
'More blurb.',
'Even more blurb. ',
'Some more blurb. ']]
这篇关于在列表中从BeautifulSoup输出拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!