Python 从文本中提取特定部分

Python 从文本中提取特定部分,python,Python,我最喜欢的 以下字符串作为输入: n [time%1:28:03::] [time] clock time n [year%1:28:01::] [year] twelvemonth, yr v [lily%1:20:00::] [lily] flower v [man%1:05:01::] [man] homo, human being, human a [government%1:14:00::] [government] authorities, regime 预期产出为: [time]

我最喜欢的

以下字符串作为输入:

n [time%1:28:03::] [time] clock time
n [year%1:28:01::] [year] twelvemonth, yr
v [lily%1:20:00::] [lily] flower
v [man%1:05:01::] [man] homo, human being, human
a [government%1:14:00::] [government] authorities, regime
预期产出为:

[time] clock time
[year] twelvemonth, yr
[lily] flower
[man] homo, human being, human
[government] authorities, regime
我已经试用过这些代码来分割和搜索我需要的文本

def space_split(a):
    if a.count(" ") == 1:
        return a.split(" ")[0]
    else:
        return " ".join(a.split(" ", 2)[2:])


print(space_split("v [wind%2:35:00::] [wind] wind up, coil the spring of a mechanism"))
我得到的结果是:

[wind] wind up, coil the spring of a mechanism

现在我如何为多个输入运行这些?有人能帮忙吗?

我相信您正在寻找一种创建分区而不是拆分的方法。 它应该解决识别您需要从中获取的相应拆分的问题

def getPartitionResult(string_input):
    _, partition_parameter ,needed_result = string_input.rpartition("[")
   needed_result = partition_parameter + needed_result
   return needed_result

if __name__ == "__main__":
    list_input = [
        "n [time%1:28:03::] [time] clock time",
        "n [year%1:28:01::] [year] twelvemonth, yr",
        "v [lily%1:20:00::] [lily] flower",
        "v [man%1:05:01::] [man] homo, human being, human",
        "a [government%1:14:00::] [government] authorities, regime"
        ]
    for input_arg in list_input:
        print getPartitionResult(input_arg)
您可以使用以下选项:

for line in list_input.split('\n'):
    print(space_split(line))
如果输入来自文件:

with open('file_path', 'r') as your_file:
    for line in your_file.readlines():
        print(space_split(line))
要将这些内容写入文件,请执行以下操作:

with open('output_file', 'w') as your_file:
    for line in list_input.split('\n'):
        output_file.write(space_split(line) + '\n')

此输入是否来自文件?您似乎得到了预期的输出。输入来自何处?如果我想将其保存到文件或在Python中写入文本文件该怎么办?此列表输入是什么,这是我们以前打印的数据列表吗?@CyleySimon是的,这是您的多行文本。csv文件中只打印最后一条记录?@CyleySimon您知道您想要什么吗?