【问题标题】:How to join all the lines together in a text file in python?如何在python的文本文件中将所有行连接在一起?
【发布时间】:2022-04-16 08:20:37
【问题描述】:

我有一个文件,当我打开它时,它会打印出一些段落。我需要将这些段落与空格连接在一起以形成一大段文本。

例如

for data in open('file.txt'):
    print data

有这样的输出:

Hello my name is blah. What is your name?
Hello your name is blah. What is my name?

输出怎么会是这样的?:

Hello my name is blah. What is your name? Hello your name is blah. What is my name?

我尝试用这样的空格替换换行符:

for data in open('file.txt'):
      updatedData = data.replace('\n',' ')

但这只是去掉了空行,并没有加入段落

并且还尝试像这样加入:

for data in open('file.txt'):
    joinedData = " ".join(data)

但是用空格分隔每个字符,同时也没有摆脱段落格式。

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用str.join:

    with open('file.txt') as f:
        print " ".join(line.strip() for line in f)  
    

    line.strip() 将删除行两端的所有类型的空格。 您可以使用line.rstrip("\n") 仅删除结尾的"\n"

    如果file.txt 包含:

    Hello my name is blah. What is your name?
    Hello your name is blah. What is my name?
    

    那么输出将是:

    Hello my name is blah. What is your name? Hello your name is blah. What is my name?
    

    【讨论】:

      【解决方案2】:

      您正在循环各个行,而 print 语句正在添加换行符。以下将起作用:

      for data in open('file.txt'):
          print data.rstrip('\n'),
      

      使用尾随逗号,print 不添加换行符,.rstrip() 调用从行中删除只是尾随换行符。

      或者,您需要将所有读取和剥离的行传递给' '.join(),而不是每一行本身。 python中的字符串是序列,因此包含在行中的字符串在传递给' '.join()时被解释为单独的字符。

      以下代码使用了两个新技巧;上下文管理器和列表理解:

      with open('file.txt') as inputfile:
          print ' '.join([line.rstrip('\n') for line in inputfile])
      

      with 语句使用文件对象作为上下文管理器,这意味着当我们完成with 语句下方缩进的块时,文件将自动关闭。 [.. for .. in ..] 语法从 inputfile 对象生成一个列表,我们将每一行转换为末尾没有换行符的版本。

      【讨论】:

      • 最佳答案在这里,尤其是第一个避免将整个文件存储在内存中的答案
      【解决方案3】:
      data = open('file.txt').read().replace('\n', '')
      

      【讨论】:

        【解决方案4】:

        如果有人在 pandas 中执行此操作,您可以在特定列中包含所有行,您可以使用以下内容:

        import pandas as pd
        
        # line is the name of the column containing all lines in df
        df.line.to_string()
        

        【讨论】:

          猜你喜欢
          • 2012-11-16
          • 1970-01-01
          • 2018-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-03
          • 2011-11-27
          • 2011-12-22
          相关资源
          最近更新 更多