【问题标题】:How to read a text file and write it with a new line whenever a comma is encountered?遇到逗号时如何读取文本文件并用新行写入?
【发布时间】:2017-09-05 21:17:05
【问题描述】:

我只是想知道一个小脚本或内置函数,它可以读取文本语料库并在解析过程中遇到逗号时用新行写入。

hello,world,rick,and,morty should be
hello,
world,
rick,
and,
morty   

【问题讨论】:

    标签: python string file io formatting


    【解决方案1】:

    不确定您的读写过程的实现,但您可以轻松地将逗号替换为逗号+换行符:

    line = line.replace(',',',\n')
    

    读取位可能是这样的:

    with open('filetoread.txt', r) as f:
      for line in f.readlines():
        line = line.replace(',',',\n')
        # ...now write these to a file or print the lines, etc.
    

    【讨论】:

    • 正则表达式会更高效吗?
    • 在这种情况下不是。 replace() 很快,re.sub() 差不多,但对于像这样一个清晰的案例来说,它就不那么简单了。
    【解决方案2】:

    您可以通过以下方式完成这项工作:

    f = open('filename', 'r+')
    n = f.read().replace(',', ',\n') # do the job!
    f.truncate(0)                    # remove file contents from begin
    f.write(n)                       # write result into file :)
    f.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多