2016-08-28 14 views
0

中括弧{inside}からテキストを抽出します。これらのテキストの相違点は、\section{または\subsection{のような接頭辞であり、すべてをそれに応じて分類します。そして、すべての終わりは次の閉じた中括弧}によって設定される必要があります。接頭辞と接尾辞の間のコンテンツを抽出する方法は?

file = "This is a string of an \section{example file} used for \subsection{Latex} documents." 

# These are some Latex commands to be considered: 

heading_1 = "\\\\section{" 
heading_2 = "\\\\subsection{" 

# This is my attempt. 

for letter in file: 
    print("The current letter: " + letter + "\n") 

Pythonを使用してLatexファイルを処理して自分のデータベースに変換したいと考えています。

+1

1) '\ section {方程式$ x_ {1 + 2} = 3}'のようなものがあればどうなりますか?ここでは名前の最後は**ではない**です。あるいは '\ section {Name \ label {label}}'と書かれています。 * *正規表現の解は脆いので、適切なLaTeXパーサを探してください。 2)あなたがしたいことはまだ明確ではありません。セクション/サブセクションのタイトルのみを気にかけていて、それをレベルとともに収集したいのですか? – Bakuriu

+0

私の状況では、 '{}'はセクション/サブセクションを終了するためだけに使用されていることが保証されています。私は、既存のNeo4jグラフデータベースのCypherコードにLatexファイルを変換するためにコンテンツを処理する必要があります。 – Liam

答えて

0

はあなただけしたい場合は、単純な正規表現を使用することができ、すべてのファイルのペア(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リストを使用して拡張可能にしたい場合は、かなり複雑になります。

+0

うわー。優れた答え。事は:我々はまだ構造を維持したい。見出し1がある場合、見出し2は何ですか? Heading_2がある場合、関連するHeadings_3は何ですか?等々。どのように入れ子になった辞書を返す正規表現を変更するには? – Liam

+0

@Liamただ正規表現を使うことはできませんが、結果を反復して連続したサブセクションをグループ化することができます。これは、セクションやサブセクションがある場合には非常に簡単です。拡張可能なソリューションが必要な場合(チャプターも追跡したい場合)、少し複雑になります。私は今私の答えを編集します。 – Bakuriu

0

正規表現モジュールを使いたいと思います。

import re 

s = "This is a string of an \section{example file} used for \subsection{Latex} documents." 

pattern = re.compile(r'\\(?:sub)?section\{(.*?)\}') 
re.findall(pattern, s) 

#output: 
['example file', 'Latex'] 
関連する問題