Skip to main content
 首页 » 编程设计

python之将字符串按单词分隔到 Python 中的单独行

2025年05月04日14lonelyxmas

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

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) 

请您参考如下方法:

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

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()。