微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

以下是我正在处理的文件

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 举报,一经查实,本站将立刻删除。