【问题标题】:Split strings in a text file into different text files将文本文件中的字符串拆分为不同的文本文件
【发布时间】:2021-06-29 06:31:24
【问题描述】:

我在一个文本文件中有以下刺痛。我将文件保存为 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")

【问题讨论】:

  • 对于文件 3:if repeat not in line and not any(i.isdigit() for i in line): ... 对于文件 4 if line.isnumeric(): ...
  • 首先,也关闭 file1 或者更好地使用上下文管理器。在这种情况下不要使用 readlines():文件描述符本身就是迭代器,你可以写 for line in file1。要获得所需的输出,请尝试以下条件:if repeat in lineelif line.isnumeric()else
  • 或@toing_noing 的方法,如果您不希望行900* 出现在任何结果文件中(它不是数字,但包含数字)
  • @toing_toing。感谢您及时的回复。它现在适用于 file3,但对于 file4,我得到的唯一输出是 900。我希望将所有数字/整数(总共 8 个值)发送到 file4
  • 你可能有空格,尝试在isnumeric()之前使用strip(),我同意@СтаниславТерляков,这种方法更干净

标签: python string split integer numbers


【解决方案1】:

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

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")

这里我添加了一个在阅读内容时删除换行符的功能

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 2012-04-21
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多