簡體   English   中英

如何使用python在文件的搜索模式的下一行中插入字符串?

[英]How insert a string in next line for searched pattern in a file using python?

我有一個包含目錄的文件,如下所示:-

He is good at python.
Python is not a language as well as animal.
Look for python near you.
Hello World it's great to be here.

現在,腳本應搜索模式“ python”或“ pyt”或“ pyth”或“ Python”或與“ p / Python”相關的任何正則表達式。 搜索特定單詞后,應插入新單詞,例如“ Lion”。 因此輸出應如下所示:

He is good at python.
Lion
Python is not a language as well as animal.
Lion
Look for python near you.
Lion
Hello World it's great to be here.

我怎樣才能做到這一點 ?

注意:-到目前為止,我編寫的代碼如下:-

def insertAfterText(args):
    file_name = args.insertAfterText[0]
    pattern = args.insertAfterText[1]
    val = args.insertAfterText[2]
    fh = fileinput.input(file_name,inplace=True)
    for line in fh:
        replacement=val+line
        line=re.sub(pattern,replacement,line)
        sys.stdout.write(line)
    fh.close()

與嘗試寫入現有文件的中間位置相比,最好編寫一個新文件。

with open是打開文件的最佳方法,因為一旦完成,它就會安全可靠地為您關閉文件。 這是使用with open一次打開兩個文件的一種很酷的方法:

import re

pattern = re.compile(r'pyt', re.IGNORECASE)

filename = 'textfile.txt'
new_filename = 'new_{}'.format(filename)

with open(filename, 'r') as readfile, open(new_filename, 'w+') as writefile:
    for line in readfile:
        writefile.write(line)
        if pattern.search(line):
            writefile.write('Lion\n')

在這里,我們要打開現有文件,並打開一個新文件(創建文件)以進行寫入。 我們遍歷輸入文件,然后簡單地將每一行寫到新文件中。 如果原始文件中的一行包含與我們的正則表達式模式匹配的內容,則在寫完原始行后,我們還會寫Lion\\n (包括換行符)。

將文件讀入變量:

with open("textfile") as ff:
  s=ff.read()

使用正則表達式並將結果寫回:

with open("textfile","w") as ff:
  ff.write(re.sub(r"(?mi)(?=.*python)(.*?$)",r"\1\nLion",s))

    (?mi): m: multiline, i.e. '$' will match end of line;
           i: case insensitiv;
    (?=.*python): lookahead, check for "python";
    Lookahead doesn't step forward in the string, only look ahead, so:
    (.*?$) will match the whole line, 
     which we replace with self '\1' and the other.

編輯:要從命令行插入使用:

import sys
textfile=sys.argv[1]
pattern=sys.argv[2]
newtext=sys.argv[3]

並更換

r"(?mi)(?=.*python)(.*?$)",r"\1\nLion"

fr"(?mi)(?=.*{pattern})(.*?$)",r"\1{newtext}"

並在open()中將“文本文件”更改為文本文件。

暫無
暫無

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

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