簡體   English   中英

創建一個正則表達式,當且僅當使用它作為條件滿足以下模式時才繼續提取信息

[英]Create a regular expression that continues to extract information if and only if the following pattern is met using it as a condition

import re

def fun(x):
    match=re.search(r"(?<=hay que) ([\w\s,]+) ([\w\s]+)",x)
    if match:
        for i in re.split(',|y',match[1]):
            with open(f'{i}.txt','w') as file:
                file.write(match[2])


input_text = str(input())
fun(input_text)

我需要創建一個正則表達式,只有在最后一個逗號,y之后才繼續匹配。 如以下示例所示,提取單詞並創建文本文件。 如果這些單詞后面跟着,y ,則繼續提取。 然后句子的結尾必須寫在每個創建的 .txt 文件的一行上。

我在使用句子時遇到問題,例如:

hay que pintar y decorar las paredes de ese lugar

生成:pintar.txt,decorar las paredes de ese.txt

在他們每個人里面寫: lugar

但應該是:

生成:pintar.txt、decorar.txt

在他們每個人里面寫: las paredes de ese lugar


其他例子...

input_sense: hay que pintar y decorar las paredes y los techos

生成:pintar.txt、decorar.txt

在他們每個人里面寫: las paredes y los techos


input_sense: hay que correr, saltar y cantar para llegar alli

生成:correr.txt、saltar.txt、cantar.txt

在他們每個人里面寫: para llegar alli


input_sense: yo creo que hay que saltar y correr para ir a ese lugar

生成:saltar.txt、correr.txt

在他們每個人里面寫: para ir a ese lugar


重要提示:如果列出的單詞以no ser|ser|no開頭

input_sense: hay que esconderse y ser silenciosos para no ser descubiertos

生成:esconderse.txt、ser_silenciosos.txt

寫在他們每個人里面: para no ser descubiertos


input_sense: hay que trabajar, escalar y no temer si quieres llegar a la meta

生成:trabajar.txt、escalar.txt、no_temer.txt

在他們每個人里面寫: si quieres llegar a la meta


我建議首先找到應該寫的內容:

x = 'hay que trabajar, escalar y no temer si quieres llegar a la meta'
s = re.search(r'( las .*)|( los .*)|( para .*)|( si .*)', x)
content = s.group(0)

然后從字符串中刪除您不想要的內容:

x = x.replace('hay que','')
x = x.replace(content, '')
x.strip()

用下划線替換特殊詞

x = x.replace(' no ', ' no_')
x = x.replace(' ser ', ' ser_')

最后拆分你的文件名

filenames = [f'{name}.txt' for name in re.split(',| y ', x)]

暫無
暫無

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

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