python re.sub换行符multiline dotall

Abu*_*esp 5 python replace newline multiline

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

"<a>https://google.com</a>",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,Dirección
Run Code Online (Sandbox Code Playgroud)

我试图删除所有逗号并将地址放一行.因此,在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()
Run Code Online (Sandbox Code Playgroud)

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

我怎么能用这个文字完成?

"<a>https://google.com</a>",Dirección
Run Code Online (Sandbox Code Playgroud)

sau*_*atz 9

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

问题的核心在于您正在将标志编译为正则表达式模式,但由于您未在替换命令中使用已编译的模式,因此无法识别它.

还有一件事.re.sub返回一个字符串,所以没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)
Run Code Online (Sandbox Code Playgroud)

如果你只是在没有编译的情况下调用re.sub,你需要调用它

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

当然,我不确切知道你的应用程序是什么,但如果你想做的就是删除所有的逗号和换行符,那么写起来可能会更清楚

replace = ''.join((c for c in text if c not in ',\n'))
Run Code Online (Sandbox Code Playgroud)