gpt4 book ai didi

python - 在读取文件期间用单个换行符替换多个换行符

转载 作者:太空狗 更新时间:2023-10-30 00:43:09 25 4
gpt4 key购买 nike

我有下一个代码,它从多个文件中读取,解析获得的行并打印结果:

import os
import re

files=[]
pars=[]

for i in os.listdir('path_to_dir_with_files'):
files.append(i)

for f in files:
with open('path_to_dir_with_files'+str(f), 'r') as a:
pars.append(re.sub('someword=|\,.*|\#.*','',a.read()))

for k in pars:
print k

但是我在输出中遇到多行换行的问题:

test1


test2

取而代之的是,我想在输出中获得没有空行的下一个结果:

 test1
test2

等等。

我尝试使用正则表达式:

pars.append(re.sub('someword=|\,.*|\#.*|^\n$','',a.read()))

但它不起作用。我还尝试使用 strip() 和 rstrip() 包括替换。它也不起作用。

最佳答案

您可以使用第二个正则表达式将多个新行替换为单个新行,并使用 strip 删除最后一个新行。

import os
import re

files=[]
pars=[]

for i in os.listdir('path_to_dir_with_files'):
files.append(i)

for f in files:
with open('path_to_dir_with_files/'+str(f), 'r') as a:
word = re.sub(r'someword=|\,.*|\#.*','', a.read())
word = re.sub(r'\n+', '\n', word).strip()
pars.append(word)

for k in pars:
print k

关于python - 在读取文件期间用单个换行符替换多个换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42629561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com