【问题标题】:Replace blank space with new line in txt file with Python用 Python 将 txt 文件中的空格替换为新行
【发布时间】:2018-04-08 21:04:46
【问题描述】:

如果我有一个包含大量数据的 .txt 文件,假设当前格式如下的电影评论:

1 达芬奇密码书真是太棒了。 1 这是我读过的第一本 clive cussler,但即使是像 Relic 和 Da Vinci code 这样的书也比这更可信。 1 我非常喜欢达芬奇密码。 1 我非常喜欢达芬奇密码。 1 我喜欢《达芬奇密码》,但它最终似乎并不属于自己。 1 一点都不夸张),半夜我们去沃尔玛买了达芬奇密码,这当然很棒。

如何更改此文件或将其内容写入新文件,以便在每个句子结束后,下一个句子从新行开始,而不是从同一行开始?

【问题讨论】:

  • 您从哪里获得这些数据?看起来你是从刮擦中得到的。在这种情况下,您可能会更幸运地尝试从原始 HTML 数据中提取格式
  • @Azsgy 它来自 Kaggle 上的示例数据集,我只是将页面保存到文件而不是抓取。

标签: python python-2.7 csv replace


【解决方案1】:

您可以在"."处拆分文本,然后使用字符串格式:

import re
new_s = ['{}\n'.format(i) for i in re.split('\.\s*', open('filename.txt').read())]
with open('movie_listing.txt', 'a') as f:
  f.write(''.join(new_s))

输出(movie_listing.txt):

1 The Da Vinci Code book is just awesome
1 this was the first clive cussler i've ever read, but even books like Relic, and Da Vinci code were more plausible than this
1 i liked the Da Vinci Code a lot
1 i liked the Da Vinci Code a lot
1 I liked the Da Vinci Code but it ultimatly didn't seem to hold it's own
1 that's not even an exaggeration ) and at midnight we went to Wal-Mart to buy the Da Vinci Code, which is amazing of course

【讨论】:

  • "\n".join(iterable) 是一种更好(也更标准)的方式
  • @Ajax1234 我应该提到我的问题的引用部分只是文件其余部分的一小部分。这将如何通过获取文件的全部内容来完成?
  • @Kizzle 你可以打开原始文件,阅读内容,然后传递给re.split。请查看我最近的编辑。
猜你喜欢
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多