python re.sub newline 多行 dotall

python re.sub newline multiline dotall

我有这个 CSV,上面写着下一行(请注意换行符 /n):

"<a>https://google.com</a>",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,Dirección

我正在尝试删除所有逗号并将地址放在第一行。因此,在 Python 我使用这个:

with open('Reutput.csv') as e, open('Put.csv', 'w') as ee:
    text = e.read()
    text = str(text)
    re.compile('<a/>*D', re.MULTILINE|re.DOTALL)
    replace = re.sub('<a/>*D','<a/>",D',text) #arreglar comas entre campos
    replace = str(replace)
    ee.write(replace)
f.close()

据我所知,re.multiline 和 re.dotall 是满足 /n 需求所必需的。我正在使用 re.compile 因为这是我知道的唯一添加它们的方法,但显然这里不需要编译它。

我怎样才能完成这篇文章?

"<a>https://google.com</a>",Dirección

当您使用 re.compile 时,您需要保存返回的 Regular Expression 对象,然后对其调用 sub。您还需要有一个 .* 来匹配任何字符,而不是匹配关闭的 html 标签。 re.MULTILINE 标志仅用于开始和结束字符串符号(^ 和 $),因此在这种情况下不需要它。

regex = re.compile('</a>.*D',re.DOTALL)
replace = regex.sub('</a>",D',text)

应该可以。您不需要将替换转换为字符串,因为它已经是一个字符串。

或者您可以编写一个不使用 .

的正则表达式
replace = re.sub('"(,|\n)*D','",D',text)

您根本不需要编译语句,因为您没有使用它。您可以将编译模式或原始模式放入 re.sub 函数中。您也不需要 MULTILINE 标志,它与您不使用的 ^ 和 $ 元字符的解释有关。

问题的核心是您正在将标志编译成正则表达式模式,但由于您没有在替换命令中使用编译后的模式,因此无法识别它。

还有一件事。 re.sub returns 一个字符串,所以 replace = str(replace) 是不必要的。

以下是对我有用的方法:

import re
with open('Reutput.csv') as e:
    text = e.read()
    text = str(text)
    s = re.compile('</a>".*D',re.DOTALL)
    replace = re.sub(s, '</a>"D',text) #arreglar comas entre campos
    print(replace)

如果不编译就直接调用re.sub,需要像

这样调用

re.sub('</a>".*D', '</a>"D', text, flags=re.DOTALL)

当然我不知道你的具体申请是什么,但是如果你只想删除所有的逗号和换行符,这样写可能更清楚

replace = ''.join((c for c in text if c not in ',\n'))

这对我有用 re.sub 和多行文本

#!/usr/bin/env python3
import re

output = open("newFile.txt","w")
input = open("myfile.txt")
file = input.read()
input.close()

text = input.read()
replace = re.sub("value1\n\s +nickname", "value\n\s +name", text, flags=re.DOTALL)
output.write(replace)
output.close()