我使用以下函数从.txt文件中提取在<html>
和<\html>
节之间找到的所有文本,使用以下函数:
def html_part(filepath):
"""
Generator returning only the HTML lines from an
SEC Edgar SGML multi-part file.
"""
start, stop = '<html>\n', '</html>\n'
filepath = os.path.expanduser(filepath)
with open(filepath) as f:
# find start indicator, yield it
for line in f:
if line == start:
yield line
break
# yield lines until stop indicator found, yield and stop
for line in f:
yield line
if line == stop:
raise StopIteration
这个函数的问题是它只获取在<html>
和<\html>
之间找到的第一个部分。但是.txt文件中还有其他部分带有<html>
和<\html>
标记。如何调整上述函数以获取在所有<html>
和<\html>
标记之间找到的所有文本?可以在here中找到示例.txt文件。你知道吗
当我执行上述功能时:
origpath = 'C:\\samplefile.txt'
htmlpath = origpath.replace('.txt', '.html')
with open(htmlpath, "w") as out:
out.write(''.join(html_part(origpath)))
您可以使用regex来执行以下操作:
您需要以一种可以多次迭代相同参数的方式来设置它。另外,是否需要用
\n
设置start
和stop
?如果<html>
不换行直接移到下面的代码中会发生什么?HTML代码的结构是这样的,所以如果需要的话,您可以在一行中编写所有内容。你知道吗因此,我首先将
start
和stop
变量更改为不包含\n
。你知道吗下一步,调整循环,使其在同一信息上重复多次
这应该可以完成这项工作,并将所有html部分分离到一个.html文件中
相关问题 更多 >
编程相关推荐