簡體   English   中英

在以下行 python

[英]finding a word on the following line python

我在一個文本文件中搜索某個字符串,然后尋找該字符串后面的另一個字符串,它可能在下一行或文檔的更下方。 我目前有

所以一個示例文本 output 想

there is a word1. then there is some more text. 
then we are looking for word2 = apple. 

我正在尋找返回單詞'apple'+ word1。 但是 word2= 可以在下一行或文檔的更下方。 我已經設法做到以下幾點,但這只有在下一行時才有效。 如果它在 3,4、5 等線上,沒有人可以幫忙嗎?

if 'word1' in line and 'word2' not in line:        
    nextLine = next(f)
    pattern = re.match('(?:word2=|word2 =)([a-z0-9_])+',nextLine) 
    if pattern:    
        print('word1', pattern)

如果我做對了,我為你做了一個例子:

string = """

there is a word1. then there is some more text. 
then we are looking for word2 = apple. 


there is a word1. then there is some more text. 
then we are looking for word2 = orange. 



there is a word1. then there is some more text. 
then there is some more text. 
then there is some more text. 
then we are looking for word2= peer. 
"""


import re
result = re.findall(".*?(word1)[\s\S]*?word2 *=.*?([a-z0-9_]+)", string)
print(result)
# should be [('word1', 'apple'), ('word1', 'orange'), ('word1', 'peer')]

注意:由於我使用整個字符串進行匹配,我的示例可能不適合大文件。

if 'word1' in line and 'word2' not in line: 
while True:       
    nextLine = next(f)
    pattern = re.match('(?:word2=|word2 =)([a-z0-9_])+',nextLine) 
    if pattern:    
        print('word1', pattern)
        break

不確定它是否會工作 無法訪問 PC 讓我知道,如果不工作我會刪除它

當心強硬:

所有無限循環都不好嗎?

while (true) 是否具有壞的編程習慣?

您應該在一個字符串中讀取完整的文件,然后試試這個。 這將捕獲 word1,以及使用捕獲組等同於 word2 的任何內容:

(word1)(?:.*[\n\r]?)+word2 ?= ?(\w+)

從您的問題中不清楚我們是否應該匹配word2 = appleword2=apple (也許您上次提到word2=這是一個錯字?),所以我包括了? 字符,這將使空格可選。

如果您希望以apple + word1格式給出答案,您可以執行以下操作:

print(pattern.group(1) + " + " + pattern.group(2))

暫無
暫無

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

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