标签内的部分文本 python
part text inside tags python
我有一个半结构化的 .txt 文件。该文件如下所示:
<tags>
blabla<text>
I want this
</text>
blabla<text>
And this
</text>
bla<text>
and this
</text>blabla
</tags>
我想获取 <text>
标签内的文本。我已经设法使用字符串分区和替换来完成它,但我认为它不是非常有效或漂亮。
这是我的代码:
with open('collection.txt') as f:
read_data = f.read()
text1 = read_data.partition("<text>")[2].partition("</text>")[0]
temp1 = read_data.replace(text1,'').replace('<text>','',1).replace('</text>','',1)
text2 = temp1.partition("<text>")[2].partition("</text>")[0]
temp2 = read_data.replace(text2,'').replace('<text>','',2).replace('</text>','',2)
text3 = temp2.partition("<text>")[2].partition("</text>")[0]
BeautifulSoup、元素树和其他 XML 解析器不工作。
关于如何改进我的代码的任何建议?我试过编译正则表达式,但无济于事。
使用 XML 解析器,例如 xml.etree
(live demo):
import xml.etree.ElementTree as ET
doc = ET.parse('collection.txt')
print([el.text.strip() for el in doc.findall('.//text')])
# output: ['I want this', 'And this', 'and this']
正则表达式是你最好的朋友!
import re
p = re.compile(r'<text>([^</]*)</text>')
result = p.findall(data_txt)
result = [x.strip() for x in result]
print(result)
您可以按如下方式使用BeautifulSoup获取所有文本条目:
from bs4 import BeautifulSoup
with open('collection.txt') as f:
read_data = f.read()
soup = BeautifulSoup(read_data, 'xml')
for text in soup.find_all('text'):
print(text.get_text(strip=True))
给你:
I want this
And this
and this
你绝对应该避免尝试使用正则表达式来进行这种解析,因为对于更复杂的示例,它很快就会失败,例如如果在数据中间使用 <!-- </text> -->
等注释,则应将其忽略。
re.findall('<text>\s*.*\s*</text>', data)
另一个解决方案
我有一个半结构化的 .txt 文件。该文件如下所示:
<tags>
blabla<text>
I want this
</text>
blabla<text>
And this
</text>
bla<text>
and this
</text>blabla
</tags>
我想获取 <text>
标签内的文本。我已经设法使用字符串分区和替换来完成它,但我认为它不是非常有效或漂亮。
这是我的代码:
with open('collection.txt') as f:
read_data = f.read()
text1 = read_data.partition("<text>")[2].partition("</text>")[0]
temp1 = read_data.replace(text1,'').replace('<text>','',1).replace('</text>','',1)
text2 = temp1.partition("<text>")[2].partition("</text>")[0]
temp2 = read_data.replace(text2,'').replace('<text>','',2).replace('</text>','',2)
text3 = temp2.partition("<text>")[2].partition("</text>")[0]
BeautifulSoup、元素树和其他 XML 解析器不工作。 关于如何改进我的代码的任何建议?我试过编译正则表达式,但无济于事。
使用 XML 解析器,例如 xml.etree
(live demo):
import xml.etree.ElementTree as ET
doc = ET.parse('collection.txt')
print([el.text.strip() for el in doc.findall('.//text')])
# output: ['I want this', 'And this', 'and this']
正则表达式是你最好的朋友!
import re
p = re.compile(r'<text>([^</]*)</text>')
result = p.findall(data_txt)
result = [x.strip() for x in result]
print(result)
您可以按如下方式使用BeautifulSoup获取所有文本条目:
from bs4 import BeautifulSoup
with open('collection.txt') as f:
read_data = f.read()
soup = BeautifulSoup(read_data, 'xml')
for text in soup.find_all('text'):
print(text.get_text(strip=True))
给你:
I want this
And this
and this
你绝对应该避免尝试使用正则表达式来进行这种解析,因为对于更复杂的示例,它很快就会失败,例如如果在数据中间使用 <!-- </text> -->
等注释,则应将其忽略。
re.findall('<text>\s*.*\s*</text>', data)
另一个解决方案