【问题标题】:Separate strings by word to a separate line in Python在Python中按单词将字符串分隔到单独的行
【发布时间】:2017-07-08 10:58:12
【问题描述】:

我的文本文件中有一行,如下所示:

hi   everyone  this is good
the weather is good     yes

我想把每个字符串写成这样的一行:

  hi
  everyone
  this

我该怎么办?我不知道每个字符串之间的空格数。

谢谢

我用过这个方法,但是没用

text_file = open("1.txt","r")
for line in text_file :
    lline = list(line)
    lline.replace(" ", "")
    line1 = lline.join()
    file.write(line1)

【问题讨论】:

    标签: python string file


    【解决方案1】:

    您可以用空格分割行并将列表展平:

    lines = ['hi there', 'how    are you   today']
    tokens = [token for line in lines for token in line.split()]
    # tokens: ['hi', 'there', 'how', 'are', 'you', 'today']
    

    从文件中读取时,代码应该是:

    with open('1.txt', 'rt') as text_file:
        tokens = [token for line in text_file for token in line.split()]
        target_file.write('\n'.join(tokens))
    

    编辑感谢officialaimm的评论,示例从re.split(r'\s+', line)简化为line.split()

    【讨论】:

    • 为什么不在字符串类本身中使用拆分?空参数split 会做我猜的工作。
    • @officialaimm,你是对的,这样会更好:)
    【解决方案2】:

    您可以只使用拆分功能。
    喜欢:

     text_file = open("1.txt","r").read()
     for i in text_file.strip().split('\n'):
        [print(j) for j in i.split()]
    ----
    hi
    everyone
    this
    is
    good
    the
    weather
    is
    good
    yes
    

    它会打印结果。

    【讨论】:

    • 它可以工作,但如果我的字符串是其他语言,我应该怎么做
    • 其他语言是什么意思?
    【解决方案3】:

    使用re.sub

    In [227]: import re
    
    In [228]: line = '''hi   everyone  this is good
         ...:   the weather is good     yes'''
    
    In [233]: print(re.sub('\s+', '\n', line, re.M | re.DOTALL))
    hi
    everyone
    this
    is
    good
    the
    weather
    is
    good
    yes
    

    【讨论】:

      【解决方案4】:

      试试这个,只要确保文件是一个为写入而打开的文件连接。

      text_file = open("1.txt","r")
      for line in text_file :
          lline = line.split()
          line1 = '\n'.join(lline)
          file.write(line1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-01
        • 2011-10-17
        相关资源
        最近更新 更多