将文本文件中的字符串拆分为不同的文本文件

2024-04-29 22:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文本文件中有以下stings。我将文件保存为file1.txt

离开的主要原因是什么

Happy Easter Holidays
All the men here are just not understanding the situation
Happy Easter Holidays
In what ways can I help you
Happy Easter Holidays
You better learn how to be polite
Happy Easter Holidays
OMG that food is looking really great
Happy Easter Holidays
Well, let us try to thing about that in another way
21
40
50
100
20
100
800
900

我想将字符串拆分为3个不同的文件(file2、file3和file4)

文件2在字符串中只包含重复的短语

文件3将包含非重复字符串,但不包含整数/数字

文件4将只包含整数/数字

我已经写了下面的代码。该代码对文件2正常工作,但对文件3和文件4无效 我需要帮助,了解如何编写适用于file3和file4的代码

file1 = open("file1.txt", "rt")
file2 = open("file2.txt", "wt")
file3 = open("file3.txt", "wt")
file4 = open("file4.txt", "wt")

content = file1.readlines()
repeat = "Happy Easter Holidays"
print("Processing inputs")

for line in content:
    if repeat in line:
        file2.write(line)
    if repeat not in line:
        file3.write(line)
    if line.isdigit():
        file4.write(line)

file2.close()
file3.close()
file4.close()

print("Output complete")

Tags: 文件字符串代码intxtlineholidaysopen
1条回答
网友
1楼 · 发布于 2024-04-29 22:15:54

在读取文件内容时,python会在每行末尾添加换行符,因此isnumeric()不起作用

file1 = open("file1.txt", "rt")
file2 = open("file2.txt", "wt")
file3 = open("file3.txt", "wt")
file4 = open("file4.txt", "wt")

def remove_newlines(fname):
    flist = open(fname).readlines()
    return [s.rstrip('\n') for s in flist]

content=remove_newlines("file1.txt")
repeat = "Happy Easter Holidays"
print("Processing inputs")

for line in content:
    if repeat in line:
        file2.write(line+"\n")
    elif line.isnumeric():
        file4.write(line+"\n")
    else:
        file3.write(line+"\n")

file2.close()
file3.close()
file4.close()

print("Output complete")

这里我添加了一个函数,在读取内容时删除换行符

相关问题 更多 >