次のような大きなテキストファイルをPythonで読んでいます(Code
とDescription
の情報が多数含まれています)。
Over-ride Flag for Site/Laterality/Morphology (Interfield Edit 42)
This field is used to identify whether a case was reviewed and coding confirmed
for paired-organ primary
site cases with an in situ behavior and the laterality is not coded right,
left, or one side involved, right or left
Origin not specified.
Code Description
Blank Not reviewed, or reviewed and corrected
1 Reviewed and confirmed as reported: A patient had behavior
code of in situ and laterality is not
stated as right: Origin of primary; left: Origin of primary; or only one side
involved, right or left
Origin not specified
This field is used to identify whether a case was reviewed and coding confirmed
for cases with a non-
specific laterality code.
Code Description
Blank1 Not reviewed
11 A patient had laterality
coded non-specifically and
extension coded specifically
This field, new for 2018, indicates whether a case was reviewed and coding
............
上記のフリーテキストから、コードと説明の値のみを次のような2つのリストに格納する必要があります。
code = ["Blank", "1", "Blank1", "11"]
des = ["Not reviewed, or reviewed and corrected", "Reviewed and confirmed as reported: A patient had behavior code of in situ and laterality is not stated as right: Origin of primary; left: Origin of primary; or only one side involved, right or left Origin not specified", "Not reviewed", "A patient had laterality coded non-specifically and extension coded specifically"]
Pythonではどうすればよいですか?
注:Code
には、「空白(または空白1)」キーワードまたは数値を含めることができます。コードDescription
が複数行に分割されている場合があります。上記の例では、1つのCode
およびDescription
ブロックに2つのコードと2つの説明が含まれていることを示しています。ただし、1つのCode
およびDescription
ブロックには、1つ以上のコードと説明を含めることができます。
次の正規表現アプローチを試してください:
blanks = re.findall(r'\bCode\b.*?\bDescription\s*?(\S+)\s+.*?\r?\n(\d+)\s+.*?(?=\r?\n\r?\n)', inp, flags=re.DOTALL)
print(blanks)
reviews = re.findall(r'\bCode\b.*?\bDescription\s*?\S+\s+(.*?)\r?\n\d+\s+(.*?)(?=\r?\n\r?\n)', inp, flags=re.DOTALL)
これは印刷します:
[('Blank', '1'), ('Blank1', '11')]
[('Not reviewed, or reviewed and corrected\n', 'Reviewed and confirmed as reported: A patient had behavior \ncode of in situ and laterality is not\nstated as right: Origin of primary; left: Origin of primary; or only one side \ninvolved, right or left\norigin not specified'), ('Not reviewed\n', 'A patient had laterality \ncoded non-specifically and\nextension coded specifically')]
ここでの考え方は、入力テキストのCode ... Description ... Blank
部分のさまざまな必要な部分を一致させてキャプチャすることです。この回答は、テキストを既にPython文字列変数に読み込んでいることを前提としています。