python - 将文本文件中的字符串拆分为不同的文本文件
问题描述
我在文本文件中有以下刺痛。我将文件保存为 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)
file2 将仅包含字符串中的重复短语
file3 将包含不重复的字符串,但没有整数/数字
file4 将仅包含整数/数字。
我已经写了下面的代码。该代码适用于 file2,但不适用于 file3 和 file4 我需要有关如何编写适用于 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")
解决方案
在读取文件的内容时,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")
在这里,我添加了一个在阅读内容时删除换行符的功能
推荐阅读
- javascript - Flex 盒子里面有 2 个 div 里面有一个画布
- java - 使用 Spring Cloud @StreamListener 接收所有类型的消息
- python - 在什么情况下 loc 和 iloc 比仅仅使用 __getitem__ 和 pandas 数据帧更好?
- python - Docker 上的气流 - 路径问题
- java - 如何解决 Intellij IDEA servlet 错误
- nginx - 无法使用公共 IP 访问配置了 nginx 的 EC2 实例
- amazon-web-services - 如何使用自定义分类器使 AWS Glue 爬网程序跳过日志文件的第一行?
- notepad++ - 在 Notepad++ 中更改不可打印字符的外观或字体
- python - 在熊猫中满足条件后按组前向填充缺失值
- php - Laravel 6 one-->资源控制器中的多关系