入力ファイルの例を次に示します。
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
HERE IS A LOT OF TEXT, THAT IS NOT INTERESTING
<br>
<div id="text"><div id="text-interesting1">11/222-AA</div>
<h2>This is the title</h2>
<P>Here is some multiline desc-<br>
cription about what is <br><br>
going on here
</div>
<div id="text2"><div id="text-interesting2">IV-VI</div>
<br>
<h1> Some really interesting text</h1>
</body>
</html>
ここで、このファイルの複数のブロックをgrepしたいと思います。たとえば、その間<div id="text-interesting1">
、</div>
次に間<P>
、</div>
次に、の間<div id="text-interesting2">
など</div>
です。重要なのは、取得したい値が複数あるということです。
これらの値をファイルに書き込みたいのですが、たとえばカンマ区切りです。どうすればそれができますか?
ルークが提供した例から、私は次のように作成しました。
import os, re
path = 'C:/Temp/Folder1/allTexts'
listing = os.listdir(path)
for infile in listing:
text = open(path + '/' + infile).read()
match = re.search('<div id="text-interesting1">', text)
if match is None:
continue
start = match.end()
end = re.search('</div>', text).start()
print (text[start:end])
match = re.search('<h2>', text)
if match is None:
continue
start = match.end()
end = re.search('</h2>', text).start()
print (text[start:end])
match = re.search('<P>', text)
if match is None:
continue
start = match.end()
end = re.search('</div>', text).start()
print (text[start:end])
match = re.search('<div id="text-interesting2">', text)
if match is None:
continue
start = match.end()
end = re.search('</div>', text).start()
print (text[start:end])
match = re.search('<h1>', text)
if match is None:
continue
start = match.end()
end = re.search('</h1>', text).start()
print (text[start:end])
print ('--------------------------------------')
出力は次のとおりです。
11/222-AA
This is the title
Some really interesting text
--------------------------------------
22/4444-AA
22222 This is the title2
22222222222222222222222
--------------------------------------
33/4444-AA
3333 This is the title3
333333333333333333333333
--------------------------------------
なぜ
一部が機能しませんか?