【问题标题】:How to reverse individual lines and words in Python3 specifically working on each paragraph in a text file?如何在 Python3 中反转单独的行和单词,专门处理文本文件中的每个段落?
【发布时间】:2020-01-19 07:56:49
【问题描述】:

基本上,我有一个文本文件:-

植物主要是多细胞的。绿色植物获得大部分 通过光合作用从阳光中获取能量。大约有320,000 植物种类。大约 260-290,000 人生产种子。绿色植物 产生氧气。

如今,绿色植物占据了大量土地。我们应该 保护我们周围的绿色植物。

我希望输出是:-

氧气。生产植物绿色种子。生产千,260-290 一些 植物。大约有 320,000 种物种有光合作用。通过 阳光从能量中获得最多的植物绿色多细胞。 主要是植物

我们。我们今天应该在这种保护的绿色植物周围。数量土地 显着占据植物绿色。

我使用split(),然后使用.join() 合并文件,但它最终颠倒了整个事情而不是逐段。

【问题讨论】:

    标签: python python-3.x split reverse


    【解决方案1】:

    更改 open("testp.txt")open("[path to your file]")

    import re
    
    text = open("testp.txt").read()
    rtext = ""
    
    for p in re.split("\n", text):
        for w in reversed(re.split(" ", p)):
            rtext += w + " "
        rtext = rtext[:-1] + "\n"
    rtext = rtext[:-1]
    
    print(rtext)
    

    更新:这个太简单了:

    import re
    
    with open("testp.txt") as f:
        print("\n".join(
            " ".join(reversed(re.split(" ", p))) for p in re.split("\n", f.read())
        ))
    
    

    更新:不使用正则表达式的代码:

    with open("testp.txt") as f:
        print("\n".join(
            " ".join(reversed(p.split())) for p in f.read().splitlines()
        ))
    

    请注意您可以使用.split("\n") 代替.splitlines()

    所有版本的结果是:

    输入:

    植物主要是多细胞的。绿色植物通过光合作用从阳光中获取大部分能量。大约有320,000种植物。大约 260–290,000 人生产种子。绿色植物产生氧气。

    如今,绿色植物占据了大量土地。我们应该保护我们周围的这些绿色植物。

    输出:

    氧气。生产植物绿色种子。生产千,260-290 一些植物。大约有 320,000 种物种有光合作用。通过阳光从能量他们的大多数获得植物绿色多细胞。主要是植物

    我们。我们今天应该在这种保护的绿色植物周围。大量土地占用植物绿色

    【讨论】:

    • 谢谢@A!但是在写回输出文件时出现错误。 with open("input.txt") as f: read_data = f.read().splitlines() with open("output.txt") as fout: for p in read_data: words = p.split() fout.write(' '.join(words[::-1])) fout.close()
    • @j_robot 也许你没有写入fout的权限;将open("output.txt") 更改为open("output.txt", "w")
    【解决方案2】:

    阅读文件并使用splitlines() 分隔段落。然后迭代段落,颠倒单词。

    with open("input.txt") as f:
        read_data = f.read().splitlines()
    
        for p in read_data:
            words = p.split()
            print(' '.join(reversed(words)))
    

    要读取和写入文件,您可以这样做:

    with open("input.txt", 'r') as f:
        read_data = f.read().splitlines()
    
    with open("output.txt", 'w') as fout:
        for p in read_data:
            words = p.split()
            fout.write(' '.join(reversed(words)))
            fout.write('\n')
    

    【讨论】:

    • 如何写回新文件? with open("input.txt") as f: read_data = f.read().splitlines() with open("output.txt") as fout: for p in read_data: words = p.split() fout.write(' '.join(words[::-1])) fout.close() 这是一个错误。
    • @j_robot 无需执行fout.close,因为您使用的是上下文管理器 (with open('..'))。当您离开 with 上下文时,该文件将自动关闭。
    • 那么我应该如何从您的代码中写入output.txt
    • 啊,明白了。谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    相关资源
    最近更新 更多