首页 > 解决方案 > Python String split() 方法 + 导出 ["eachpieces split"] 在不同的 .txt 文件中

问题描述

Python String split() 方法 + 导出 ["eachpieces split"] 在不同的 .txt 和 .jpg 文件中,为每种文件类型指定路径文件夹

您好,我学习 Python,我必须对文本进行不同的操作:

  1. 拆分文本
  2. 打印拆分文本

  1. 将print(x) 中包含的["each pieces split"] 导出到不同的 .txt 和 .jpg 文件,并为每种文件类型指定路径文件夹

步骤 1 和 2 已完成:

    txt = "This is the first sentence. Then, the second                               
    sentence. And at the end, the last sentence."
    
    x = txt.split (".")

    print(x)

    ['This is the first sentence', ' Then the second sentence',   
    ' And at the end, the last sentence', '']

我尝试做的事情:

  1. 将print(x) 中包含的["each pieces split"] 导出到不同的 .txt 和 .jpg 文件,并为每种文件类型指定路径文件夹

有人知道我们怎么能做出这样的事情吗?


谢谢你的帮助

标签: pythontextsplitexporttxt

解决方案


方法之一:

txt = """This is the first sentence. Then, the second                               
sentence. And at the end, the last sentence."""

sentences = txt.split (".")
path_to_files = 'C:\\Users\\username\\Desktop\\Split txt export'
for index in range(len(sentences)):
    with open(f'{path_to_files}\\file_{index}', 'w') as f:
        f.write(sentences[index])

这是你想要的吗?在上述方法中,将根据形成的句子数量创建文件。因此,如果有 10 个句子,则在一个文件夹中会创建 10 个文件。


推荐阅读