【问题标题】:trying to replace "." with new line (\n) in python, without space after the "."试图替换“。”在 python 中使用新行 (\n),“。”后没有空格
【发布时间】:2019-08-03 12:57:23
【问题描述】:

我正在尝试替换“。”在 python 中使用新行 ("\n")。

input file:
abc. abc
def. def

new input:
Nigel Reuben Rook Williams (15 July 1944 – 21 April 1992) was an English conservator and expert on the restoration of ceramics and glass. From 1961 until his death he worked at the British Museum, where he became the Chief  successful restorations of the Sutton Hoo helmet and the Portland Vase.

Joining

代码:

test_file=open(path,'r')
test_file_1=open(new_path,'w')

for line in test_file:
    test_file_1.write(line.replace('.','\n'))

test_file.close()
test_file_1.close()

我想删除换行前的空格。

expected new output:
nigel reuben rook williams july april was an english  restoration of ceramics and glass
from until his death he worked at the british museum where he became the 
chief conservator of ceramics and glass in
there his work included the successful restorations of the sutton hoo helmet 
and the portland vase
joining

【问题讨论】:

  • line.replace('. ','\n') - _
  • @OlvinR​​oght 还有 2 个问题:1- 我在文本文件中有一行,例如:“hello.world lala”。为了第一 ”。”替换工作,用于第二个“。”在行尾它不起作用。 2-我也想删除两行之间的差距。例如“abc”,然后是新行和另外 1 行的空白(我想删除)
  • 您愿意在您的问题中提供真实的输入/输出吗?
  • 当然,看看 new_input。
  • @OlvinR​​oght 当然,看看 new_input。

标签: python replace newline strip


【解决方案1】:

在点之后,有空格。你可以使用line.replace('. ','\n')

或者你可以使用:

for line in test_file:
    words = line.split('.')
    for word in words:
        test_file_1.write(word.strip()+'\n')

【讨论】:

  • 但是.. line.split('. ')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 2016-10-23
  • 2018-02-05
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
相关资源
最近更新 更多