はあなただけしたい場合は、単純な正規表現を使用することができ、すべてのファイルのペア(section-level, title)
:codewords
リストの値を変更することにより
In [15]: text = '''
...: \section{First section}
...:
...: \subsection{Subsection one}
...:
...: Some text
...:
...: \subsection{Subsection two}
...:
...: Other text
...:
...: \subsection{Subsection three}
...:
...: Some other text
...:
...:
...: Also some more text \texttt{other stuff}
...:
...: \section{Second section}
...:
...: \section{Third section}
...:
...: \subsection{Last subsection}
...: '''
In [16]: regex.findall(text)
Out[16]:
[('section', 'First section'),
('subsection', 'Subsection one'),
('subsection', 'Subsection two'),
('subsection', 'Subsection three'),
('section', 'Second section'),
('section', 'Third section'),
('subsection', 'Last subsection')]
:
import re
codewords = [
'section',
'subsection',
# add other here if you want to
]
regex = re.compile(r'\\({})\{{([^}}]+)\}}'.format('|'.join(re.escape(word) for word in codewords)))
使用例をより多くの種類のコマンドに一致することができます。ファイルにこれを適用するに
単にread()
それは最初:
with open('myfile.tex') as f:
regex.findall(f.read())
あなたはすべてのこれらのコマンドは、同じ行にある保証を持っているなら、あなたはより多くのメモリ効率的かつ実行することができます。
Fとしてオープン( 'myfile.tex')を持つ: 結果= [] Fの行のための : results.extends(regex.findall(ライン))
それとも、ビットカ月になりたい場合は空想RE:
from itertools import chain
with open('myfile.tex') as f:
results = chain.from_iterable(map(regex.findall, f))
注しかし、あなたのようなものがあればということ:
\section{A very
long title}
をこれが失敗し、なぜread()
を使用したソリューションは、あまりにもそのセクションを取得します。
いずれにしても、フォーマットのわずかな変更がこれらの種類のソリューションを壊すことに注意する必要があります。このように、より安全な代替手段としては、適切なLaTeXパーサを探す必要があります。
特定のセクションに「含まれている」サブセクションをグループ化する場合は、上記の解決策で結果を取得した後に行うことができます。 itertools.groupby
のようなものを使用しなければなりません。 itertoolsから
はGROUPBYをインポートし、カウントし、チェーン
results = regex.findall(text)
def make_key(counter):
def key(match):
nonlocal counter
val = next(counter)
if match[0] == 'section':
val = next(counter)
counter = chain([val], counter)
return val
return key
organized_result = {}
for key, group in groupby(results, key=make_key(count())):
_, section_name = next(group)
organized_result[section_name] = section = []
for _, subsection_name in group:
section.append(subsection_name)
そして、最終的な結果は次のようになります。ポストの先頭にテキストの構造と一致した
In [12]: organized_result
Out[12]:
{'First section': ['Subsection one', 'Subsection two', 'Subsection three'],
'Second section': [],
'Third section': ['Last subsection']}
。
これをcodewords
リストを使用して拡張可能にしたい場合は、かなり複雑になります。
1) '\ section {方程式$ x_ {1 + 2} = 3}'のようなものがあればどうなりますか?ここでは名前の最後は**ではない**です。あるいは '\ section {Name \ label {label}}'と書かれています。 * *正規表現の解は脆いので、適切なLaTeXパーサを探してください。 2)あなたがしたいことはまだ明確ではありません。セクション/サブセクションのタイトルのみを気にかけていて、それをレベルとともに収集したいのですか? – Bakuriu
私の状況では、 '{}'はセクション/サブセクションを終了するためだけに使用されていることが保証されています。私は、既存のNeo4jグラフデータベースのCypherコードにLatexファイルを変換するためにコンテンツを処理する必要があります。 – Liam