Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在python中删除文本文件中的换行符_Python_Replace_Strip - Fatal编程技术网

无法在python中删除文本文件中的换行符

无法在python中删除文本文件中的换行符,python,replace,strip,Python,Replace,Strip,冒着名誉扫地的危险,我不知道还能做什么。我的文件没有显示任何隐藏字符,我已经尝试了我能想到的每个.replace和.strip。我的文件是UTF-8编码的,我使用的是python/3.6.1 我有一个格式如下的文件: >header1 AAAAAAAA TTTTTTTT CCCCCCCC GGGGGGGG >header2 CCCCCC TTTTTT GGGGGG AAAAAA 我试图删除文件末尾的换行符,使每一行成为一个连续的字符串。(此文件实际上有数千行长

冒着名誉扫地的危险,我不知道还能做什么。我的文件没有显示任何隐藏字符,我已经尝试了我能想到的每个.replace和.strip。我的文件是UTF-8编码的,我使用的是python/3.6.1 我有一个格式如下的文件:

 >header1
 AAAAAAAA
 TTTTTTTT
 CCCCCCCC
 GGGGGGGG

 >header2
 CCCCCC
 TTTTTT
 GGGGGG
 AAAAAA
我试图删除文件末尾的换行符,使每一行成为一个连续的字符串。(此文件实际上有数千行长)。 我的代码是多余的,因为我输入了所有我能想到的删除换行符的内容:

 fref = open(ref)
 for line in fref:
     sequence = 0
     header = 0
     if line.startswith('>'):
          header = ''.join(line.splitlines())
          print(header)
     else:
          sequence = line.strip("\n").strip("\r")
          sequence = line.replace('\n', ' ').replace('\r', '').replace(' ', '').replace('\t', '')
          print(len(sequence))
输出为:

 >header1
 8
 8
 8
 8
 >header2
 6
 6
 6
 6
但如果我手动进入并删除行尾,使其成为一个连续字符串,它将显示为一个全等字符串

预期产出:

 >header1
 32
 >header2
 24     
提前感谢您的帮助,
丹尼斯

根据我对你问题的理解,你会喜欢这样: 注意序列是如何在循环的多个迭代步骤上构建的,因为您希望组合多行

with open(ref) as f:
    sequence = "" # reset sequence
    header = None
    for line in f:
        if line.startswith('>'):
            if header:
                print(header)        # print last header
                print(len(sequence)) # print last sequence
            sequence = ""      # reset sequence
            header = line[1:]  # store header
        else:
            sequence += line.rstrip()   # append line to sequence

根据我对你的问题的理解,你希望这样: 注意序列是如何在循环的多个迭代步骤上构建的,因为您希望组合多行

with open(ref) as f:
    sequence = "" # reset sequence
    header = None
    for line in f:
        if line.startswith('>'):
            if header:
                print(header)        # print last header
                print(len(sequence)) # print last sequence
            sequence = ""      # reset sequence
            header = line[1:]  # store header
        else:
            sequence += line.rstrip()   # append line to sequence

有几种方法可以解析这种输入。在所有情况下,我建议将打开打印的副作用隔离在功能之外,您可以通过单元测试来说服自己正确的行为

您可以迭代每一行,并分别处理空行和文件结尾的情况。在这里,我使用yield语句返回值:

def parse(infile):
    for line in infile:
        if line.startswith(">"):
            total = 0
            yield line.strip()
        elif not line.strip():
            yield total
        else:
            total += len(line.strip())
    if line.strip():
        yield total

def test_parse(func):
    with open("input.txt") as infile:
        assert list(parse(infile)) == [
            ">header1",
            32,
            ">header2",
            24,
        ]
或者,您可以同时处理空行和文件结尾。在这里,我使用一个输出数组,在其中附加标题和总计:

def parse(infile):
    output = []
    while True:
        line = infile.readline()
        if line.startswith(">"):
            total = 0
            header = line.strip()
        elif line and line.strip():
            total += len(line.strip())
        else:
            output.append(header)
            output.append(total)
            if not line:
                break

    return output

def test_parse(func):
    with open("input.txt") as infile:
        assert parse(infile) == [
            ">header1",
            32,
            ">header2",
            24,
        ]
或者,您也可以将整个输入文件拆分为空行分隔块,并单独解析它们。这里,我使用一个输出流,将输出写入其中;在生产中,您可以传递sys.stdout流,例如:

import re
def parse(infile, outfile):
    content = infile.read()
    for block in re.split(r"\r?\n\r?\n", content):
        header, *lines = re.split(r"\s+", block)
        total = sum(len(line) for line in lines)
        outfile.write("{header}\n{total}\n".format(
            header=header,
            total=total,
        ))

from io import StringIO
def test_parse(func): 
    with open("/tmp/a.txt") as infile: 
        outfile = StringIO() 
        parse(infile, outfile) 
        outfile.seek(0) 
        assert outfile.readlines() == [ 
            ">header1\n", 
            "32\n", 
            ">header2\n", 
            "24\n", 
        ]

请注意,为了简洁起见,我的测试使用了open(“input.txt”),但实际上我建议传递一个StringIO(…)实例,以便更容易地查看正在测试的输入,避免命中文件系统并加快测试速度。

有几种方法可以解析此类输入。在所有情况下,我建议将打开打印的副作用隔离在功能之外,您可以通过单元测试来说服自己正确的行为

您可以迭代每一行,并分别处理空行和文件结尾的情况。在这里,我使用yield语句返回值:

def parse(infile):
    for line in infile:
        if line.startswith(">"):
            total = 0
            yield line.strip()
        elif not line.strip():
            yield total
        else:
            total += len(line.strip())
    if line.strip():
        yield total

def test_parse(func):
    with open("input.txt") as infile:
        assert list(parse(infile)) == [
            ">header1",
            32,
            ">header2",
            24,
        ]
或者,您可以同时处理空行和文件结尾。在这里,我使用一个输出数组,在其中附加标题和总计:

def parse(infile):
    output = []
    while True:
        line = infile.readline()
        if line.startswith(">"):
            total = 0
            header = line.strip()
        elif line and line.strip():
            total += len(line.strip())
        else:
            output.append(header)
            output.append(total)
            if not line:
                break

    return output

def test_parse(func):
    with open("input.txt") as infile:
        assert parse(infile) == [
            ">header1",
            32,
            ">header2",
            24,
        ]
或者,您也可以将整个输入文件拆分为空行分隔块,并单独解析它们。这里,我使用一个输出流,将输出写入其中;在生产中,您可以传递sys.stdout流,例如:

import re
def parse(infile, outfile):
    content = infile.read()
    for block in re.split(r"\r?\n\r?\n", content):
        header, *lines = re.split(r"\s+", block)
        total = sum(len(line) for line in lines)
        outfile.write("{header}\n{total}\n".format(
            header=header,
            total=total,
        ))

from io import StringIO
def test_parse(func): 
    with open("/tmp/a.txt") as infile: 
        outfile = StringIO() 
        parse(infile, outfile) 
        outfile.seek(0) 
        assert outfile.readlines() == [ 
            ">header1\n", 
            "32\n", 
            ">header2\n", 
            "24\n", 
        ]

请注意,为了简洁起见,我的测试使用了open(“input.txt”),但实际上我建议传递一个StringIO(…)实例,以便更容易地查看正在测试的输入,避免命中文件系统并加快测试速度。

您能显示您期望的输出吗,您可以使用
for line in fref:
逐行迭代您的文件,并在每次迭代中打印这一行(经过一些基本不起任何作用的处理)。当然,你仍然会得到多行输出,你期望得到什么?@Guillaume我编辑了这个问题以反映你的输入。谢谢<代码>如果line.startswith('>'):打印('\n%s'%line.strip());其他:打印(line.strip(),end='')。您正在成功删除每行末尾的换行符。你应该考虑,也许你要解决的问题比这更牵涉其中。似乎您打算
行连接起来?您能显示您期望的输出吗?好吧,您使用fref:中的行对文件进行逐行迭代,并在每次迭代中打印该行(经过一些基本上不起任何作用的处理之后)。当然,你仍然会得到多行输出,你期望得到什么?@Guillaume我编辑了这个问题以反映你的输入。谢谢<代码>如果line.startswith('>'):打印('\n%s'%line.strip());其他:打印(line.strip(),end='')。您正在成功删除每行末尾的换行符。你应该考虑,也许你要解决的问题比这更牵涉其中。似乎您打算
加入
行?非常接近,但是输出给我:>header>header2(序列长度2)非常接近,但是输出给我:>header>header2(序列长度2)感谢您的响应,您所有的答案都返回与peter在下面发布的结果相同的结果
\n'
>header2'\n'
24
谢谢您的回复,您所有的答案都返回与peter在下面发布的结果相同
\n'
>header2'\n'
24