【问题标题】:Removing a particular pattern of a text file in python [duplicate]在python中删除文本文件的特定模式[重复]
【发布时间】:2021-11-30 17:35:39
【问题描述】:

我有一个名为 file1 的输入文件,其中包含:

学生 0:表现不错,但可以做得更好。 [76.50%]

学生 1:出色的表现。 [98.50%]

在这个特定文件中,我只想删除 % 部分,以便它产生如下输出:

学生 0:表现不错,但可以做得更好。

学生 1:出色的表现。

我尝试过这种方式:

with open('file1', 'r') as infile, open('file2', 'w') as outfile:
    temp = infile.read().replace("[[0-9]+]", "").replace("%","")
    outfile.write(temp)

但这只是删除 %sign 并给出输出:

学生 0:表现不错,但可以做得更好。 [76.50]

学生 1:出色的表现。 [98.50]

【问题讨论】:

    标签: python python-3.x regex file


    【解决方案1】:

    你仍然需要正则表达式:

    import re
    with open('file1', 'r') as infile, open('file2', 'w') as outfile:
        temp = re.sub("\[[\d+\.%]+\]", "", infile.read())
        outfile.write(temp)
    

    【讨论】:

    • 它发出警告说:“FutureWarning:可能嵌套在位置 1 temp = re.sub("[[0-9]+]", "", infile.read()) .replace("%","")"
    • @Dev 检查我的编辑
    • 好的,谢谢。现在我得到了我想要的输出,但未来的警告仍然存在。你能帮忙吗?
    • @Dev 检查我的编辑
    猜你喜欢
    • 2018-07-27
    • 1970-01-01
    • 2016-05-03
    • 2021-03-11
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多