正規表現で検索語を検索し、結果を別のデータファイルに配置しますか?

StackOverflow https://stackoverflow.com//questions/12685368

質問

この質問のタイトルが正しいかどうかわからないので、少し背景情報を教えてください。私は2つのテキストファイルを持っています。データと呼ばれるもの。txtと他の結果と呼ばれます。txt。データファイルには、Ciscoネットワークデバイス上の「バージョンの表示」の結果があります。次のようになります:

Cisco IOS Software, s72033_rp Software (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2(33)SXI4, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Sat 29-May-10 17:54 by prod_rel_team

ROM: System Bootstrap, Version 12.2(17r)SX6, RELEASE SOFTWARE (fc1)

 core-router uptime is 2 years, 5 weeks, 1 day, 5 hours, 47 minutes
Uptime for this control processor is 2 years, 5 weeks, 1 day, 4 hours, 50 minutes
Time since san-qrc1 switched to active is 2 years, 5 weeks, 1 day, 4 hours, 56 minutes
System returned to ROM by reload at 16:12:08 PDT Fri Aug 27 2010 (SP by reload)
System restarted at 16:19:33 PDT Fri Aug 27 2010
System image file is "sup-bootdisk:s72033-advipservicesk9_wan-mz.122-33.SXI4.bin"
Last reload reason: Reload Command



This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

cisco WS-C6509-E (R7000) processor (revision 1.5) with 983008K/65536K bytes of memory.
Processor board ID XXXXXXXXXX
SR71000 CPU at 600Mhz, Implementation 0x504, Rev 1.2, 512KB L2 Cache
Last reset from s/w reset
35 Virtual Ethernet interfaces
51 Gigabit Ethernet interfaces
26 Ten Gigabit Ethernet interfaces
1917K bytes of non-volatile configuration memory.
8192K bytes of packet buffer memory.

65536K bytes of Flash internal SIMM (Sector size 512K).
Configuration register is 0x2102

簡単に言えば、データを読みたいです。txtと特定の文字列を引き出し、結果に入れます。txt。CSV形式はいいでしょうが、データを抽出するだけで満足しています。

たとえば、このスクリプトは、デバイスのホスト名(この場合はcore-router)、システムイメージファイル名(s72033-advipservicesk9_wan-mz)などの関連データを引き出します。122-33.SXI4.ビン)、稼働時間(2年、5週、1日、5時間、47分)、シリアル番号(XXXXXXXX)、およびモデル(WS-C6509-E)。そのすべての情報は、結果にタブ区切り形式で配置されます。txt。

将来的には、異なるデータ。txtファイルを利用することができ、データは結果に追加されます。txt、私にデータポイントの実行中の集計を与えます。私はそれが理にかなっていることを願っています。私は探しているものに関して検索をしようとしましたが、私が見つけたもののほとんどは、テキストファイル内の行全体を見つけるか、単語の出現のインデックス番号を取得することについて話しています。

最後に一つ:Ciscoデバイスのモデルによって、すべての項目は異なっています。その周りの言葉は一般的に同じになりますが、私が探しているアイテムは異なります。あなたが提供できるどの援助でも非常に認められます。事前に感謝します。

更新

私はあなたが提供したスクリプトを利用しましたが、私はまだ次のように見えます:

python
Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("data.txt") as infile:
...     text = infile.read()
... 
>>> import re
>>> regex = re.compile(
...     r"""^(?P<device>\S*)           # Match non-whitespace device name
...     \suptime\sis\s                 # Match " uptime is "
...     (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
...     .*?^System\simage\sfile\sis\s  # Match intervening text
...     "[^:]*:                        # Match from quote to colon
...     (?P<sifilename>[^"]*)          # Match everything until quote --> filename
...     .*?^cisco\s                    # Match intervening text
...     (?P<model>\S*)                 # Match non-whitespace model name
...     .*?^Processor\sboard\sID\s     # Match intervening text
...     (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
...     re.DOTALL | re.MULTILINE | re.VERBOSE)
>>> match = regex.search(text)
>>> match.groups()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'

問題は、ホスト名が1スペースでインデントされていることです。貼り付けるとインデントが消えました。ただし、コマンド"show version"が発行されると、その1つのスペースインデントが表示されます。上記のコードを実行しようとすると、スクリプトが壊れます。スペースを削除すると、それが機能することができます。

役に立ちましたか?

解決

ファイルを次のような文字列に読み込むことができます:

with open("data.txt") as infile:
    text = infile.read()

次に、正規表現を使用して関連情報を抽出できます:

import re
regex = re.compile(
    r"""^(?P<device>\S*)           # Match non-whitespace device name
    \suptime\sis\s                 # Match " uptime is "
    (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
    .*?^System\simage\sfile\sis\s  # Match intervening text
    "[^:]*:                        # Match from quote to colon
    (?P<sifilename>[^"]*)          # Match everything until quote --> filename
    .*?^cisco\s                    # Match intervening text
    (?P<model>\S*)                 # Match non-whitespace model name
    .*?^Processor\sboard\sID\s     # Match intervening text
    (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
    re.DOTALL | re.MULTILINE | re.VERBOSE)
match = regex.search(text)

今すぐ match.groups() 含まれています:

>>> match.groups()
('core-router', '2 years, 5 weeks, 1 day, 5 hours, 47 minutes', 
's72033-advipservicesk9_wan-mz.122-33.SXI4.bin', 'WS-C6509-E', 'XXXXXXXXXX')

これを使用して、次のようにcsvファイルに書き込むことができます:

import csv
with open("results.txt", "a") as outfile:
    outcsv = csv.Writer(outfile)
    outcsv.writerow(match.groups())
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top