簡體   English   中英

如何使用正則表達式將字符串放在 python 中某個“單詞”的前面?

[英]How to put strings in front of a certain 'word' in python by using regular expression?

我在 python 中使用正則表達式時遇到了一些問題。

如下例所示,

我想要做的是把'string_1'放在以字母'past'開頭的段落前面。(參考下面的代碼)

輸入.txt

some random texts (100+ lines)
bbb
...
ttt

modern_b different_story(
...
some random texts
...
);

past_c different_story(

...
some random texts
...
);

所需 output.txt

some random texts (100+ lines)
bbb
...
ttt

modern_b different_story(
...
some random texts
...
);

java is fun; 
python is fun;

past_c different_story(

...
some random texts
...
);

好的,那么這是我到目前為止的代碼:

import re

output_file = open('output.txt', 'w')
input_file = open('input.txt', 'r')

string_1 = 'java is fun; \npython is fun;'

t = re.sub(
    '(?=\s*^past)',
    '\n' + string_1 + '\n' ,
    input_file.read(),
    0,
    re.M
)

output_file.write(t)

當我運行此代碼時,output 出現在“past_c”前面,但它帶有多個相同的行。我只需要字符串“一次”。 我想我幾乎到達了終點。 但是現在多條線似乎在脖子上疼痛..我假設繩子足夠長。 我只需要參考下一段,而不是上一段(在這種情況下為'past_c'。)你能給我任何想法來糾正這個問題嗎? 或者,也歡迎任何更有效的方法來實現這一點!! 謝謝

您可以使用以下內容來實現您想要的我的想法:

import re

with open("input.txt", "r") as inp:
    with open("output.txt", "w") as oup:
        for i in inp:
            oup.write("my_string " + i) if re.match("^a", i) else oup.write(i)

基本上,如果一行以“a”開頭,則添加“my_string”並將該行寫入 output 文件,否則它只是將該行復制到 output 文件

下面的這個片段做同樣的事情,但將它寫入同一個文件:

import re

with open("input.txt", "r") as inp:
    my_list = []
    for i in inp:
        my_list.append(("my_string " + i)) if re.match("^a", i) else my_list.append(i)

with open("input.txt", "w") as inp:
    inp.write("".join(my_list))

積極展望未來可能會有所幫助。

text = '''

bbb
...
ttt

modern_b different_story(
...
some random texts
...
);

past_c different_story(

...
some random texts
...
);

'''


re.sub(r'(?=past_c different_story)', r'java is fun;\npython is fun;\n\n', text)


bbb
...
ttt

modern_b different_story(
...
some random texts
...
);

java is fun;
python is fun;

past_c different_story(

...
some random texts
...
);


def fun1(text, st):
    return re.sub(r'(?=past_c different_story)', fr'{st}', text)


fun1(text, 'java is fun;\npython is fun;\n\n')


bbb
...
ttt

modern_b different_story(
...
some random texts
...
);

java is fun;
python is fun;

past_c different_story(

...
some random texts
...
);

暫無
暫無

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

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