从右到左反转文本并举例

问题描述 投票:0回答:1

我想要这个 文本是这样的样本

样品

这个:

hello all my name nora

像这样:

nora name my all hello

当然,重要的一点是,这不仅仅是一篇文本,我需要多篇文本同时以这种方式出现,谢谢。

如果可以在记事本++或工具中使用正则表达式,我将不胜感激谢谢🙏🙏

python c# text notepad++
1个回答
0
投票

我没听说过这样的工具。然而,我创建了这个简单的程序。它可以在不同的操作系统上运行。只需插入您想要反转行的文件的名称,整个文件(每一行都有自己的行)就会被反转。

例如

文件.txt

consequat quis nostrud exercitation ullamco laboris nisi ut aliquip
sunt in culpa qui officia deserunt mollit anim id est laborum
eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident

例如(程序运行后)

文件.txt

aliquip ut nisi laboris ullamco exercitation nostrud quis consequat
laborum est id anim mollit deserunt officia qui culpa in sunt
proident non cupidatat occaecat sint Excepteur pariatur nulla fugiat eu

程序源码及使用:

蟒蛇

程序员对此的处理方法:

将这段程序保存在.py文件中(例如script.py) 然后在你的终端上:

import argparse
import os

def reverse_sentences_in_file(input_file):
    # Read the file
    with open(input_file, 'r') as file:
        lines = file.readlines()

    # Process each line
    reversed_lines = []
    for line in lines:
        # Strip newline characters and split the line into words
        words = line.strip().split()
        # Reverse the order of words
        reversed_words = words[::-1]
        # Join the reversed words back into a sentence
        reversed_line = ' '.join(reversed_words)
        # Append the reversed sentence to the list
        reversed_lines.append(reversed_line)

    # Write the reversed sentences back to the same file
    with open(input_file, 'w') as file:
        for reversed_line in reversed_lines:
            file.write(reversed_line + '\n')

def main():
    # Setup argument parser
    parser = argparse.ArgumentParser(description="Reverse sentences in multiple files.")
    parser.add_argument('files', metavar='F', type=str, nargs='+', help='a list of files to process')

    # Parse arguments
    args = parser.parse_args()

    # Reverse sentences in each file
    for input_file in args.files:
        if os.path.isfile(input_file):
            reverse_sentences_in_file(input_file)
            print(f"Reversed sentences have been written to {input_file}.")
        else:
            print(f"File {input_file} does not exist.")

if __name__ == '__main__':
    main()

应用程序使用:

python script.py name_of_the_file_you_want_to_reverse.txt

© www.soinside.com 2019 - 2024. All rights reserved.