簡體   English   中英

使用Python查找不同行上的2個相關字符串

[英]using Python to find 2 related strings that are on different lines

我編寫了一個程序,在遍歷從中收集信息的許多設備之后,該程序將數據輸出到大文件中。
來自新設備的新信息將附加到此文件上,因此它基本上是一個大文件,每10行左右具有相似(但不完全)相同的信息。

我需要做的是查找一個特定的字符串(在這種情況下,我在大文件中的每次數據迭代中都使用了一個用於識別目的的特殊字符),然后獲取該特定識別字符之后的文本, 2行。 布朗尼指出是否可以讓我檢查這是否是我要查找的正確數據(即包含“版本”一詞)。

例如,文本文件可能如下所示:

trying 1.1.1.1
connected to 1.1.1.1
username: xxxx
password: xxxx
>>2001
issue command y
y = version                                

上面的文本將重復大約100次,並在“ >>”之后列出唯一的標識符。 我需要在Python中執行的操作是打開包含文本的文件,循環遍歷,找到“ >>”並收集下面兩行列出的版本。 然后,我需要以顯示“ >> 2001 y =版本”的方式在屏幕上進行打印,一直循環到“ >> 2099 y =版本”。

正則表達式將是一個很好的工具。 例如:

# you'll want to load this from an actual file instead; 
# I'm just including it as a literal for example
file_contents = '''trying 1.1.1.1
connected to 1.1.1.1
username: xxxx
password: xxxx
>>2001
issue command y
y = version'''


# Summary of this regex: find and capture your ">>2001" line,
# followed by a line that doesn't get captured, followed by a line that gets captured
matches = re.compile('\n(>>\d+)\n.*\n(.*)\n?').findall(file) 
# matches should now be [('>>2001', 'y = version')]

for match in matches:
    print(match[0], match[1])`

歡迎來到美好的正則表達式世界!

您可以在regexpal上試用此regex

您可以將文件讀入列表並在列表中loop查找您的標識符,然后打印所需的項目。 例如:

碼:

with open('test.txt', 'r') as f:
    data = f.read().splitlines()
    for line in data:
        if line.startswith('>>'):
            print line, data[data.index(line)+2]

輸入文件:

trying 1.1.1.1
connected to 1.1.1.1
username: xxxx
password: xxxx
>>2001
issue command y
y = version
>>2002
issue command y
y = versionx
>>2003
issue command y
y = versionz

輸出:

>>2001 y = version
>>2002 y = versionx
>>2003 y = versionz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM