使用 python 多次打印文本文件中两个单词之间的文本



这是我的文本文件中的文本。

<a>
Some Text 1.....
</a>
Some Other Text
<a>
Some Text 2.....
</a>
Some Other Text
<a>
Some Text 3.....
</a>

我需要在标签之间提取字符串,并使用python 2.7/3将每个字符串写入单独的文本文件中。

波纹管代码只返回第一个标签之间的字符串,不考虑文本的其余部分。

with open('myfile.txt', 'r') as inF:
for num, line in enumerate(inF,1):
if '</a>' in line:
targetline = num+1
f = open("myfile.txt")
aa = ""
for i in range(targetline):
aa += f.next().strip() + "n"
f.close()
fout = open("MyData1.txt", "w")
finaltext = (aa.split('<a>'))[1].split('</a>')[0]
fout.write(finaltext)
fout.close()

你有什么想法吗?

使用BeautifulSoup

演示:

from bs4 import BeautifulSoup
with open(filename, 'r') as f, open(filename1, 'w') as outfile:
soup = BeautifulSoup(f.read(), "html.parser")
for i in soup.find_all("a"):
print(i.text.strip())
outfile.write(i.text.strip() + "n")     #Write to new File

输出:

Some Text 1.....
Some Text 2.....
Some Text 3.....

最新更新