如何从文件行中去除换行符?

问题描述

下面是读取文件并返回没有注释的内容并连接以“//”结尾的行的代码

(?<=\/)[^\/]+$

以下是我正在处理的文件

index.html

下面是这段代码输出

def get_lines(path: str) -> Iterator[str]:

    """ Function to print lines of a given file and remove comments"""

    output: str = ''
    with open(path,encoding='utf-8') as filehandle:
        lines: get_lines = filehandle.readline()
        for lines in filehandle:
    
            if lines.startswith('#'):
                while lines.rstrip().endswith('\\'):
                    next_line = next(filehandle)
                    lines = lines.rstrip()[:-1] + next_line
               continue
            else:
        
                while lines.rstrip().endswith('\\'):
                    next_line = next(filehandle)
                    lines = lines.rstrip()[:-1] + next_line
                output += lines
                output = lines.split("#",1)
                lines = output[0].strip('\n')
        
            while lines.rstrip().endswith('\\'):
                next_line = next(filehandle)
                lines = lines.rstrip()[:-1] + next_line
                lines.strip('\n')
    
            yield lines
    
g = get_lines('C:\\Users\Swayam\Documents\ok2.txt')
for x in g:
    x.strip('\n')
    print (x)

预期输出

# this entire line is a comment - don't include it in the output
<line0>
# this entire line is a comment - don't include it in the output
<line1># comment
<line2>
# this entire line is a comment - don't include it in the output
<line3.1 \ #world 
line3.2 \
line3.3>
<line4.1 \ 
line4.2>
<line5># comment \
# more comment1 \
more comment2>
<line6>
# here's a comment line continued to the next line \
this line is part of the comment from the prevIoUs line

如何去掉这个换行符?我在代码的几乎所有部分都添加了 strip 但显然不起作用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)