【问题标题】:To delete string contents from file using python list使用 python list 从文件中删除字符串内容
【发布时间】:2021-09-24 16:22:32
【问题描述】:

使用 python,我试图从 input_file 中删除字符串内容,所以在我的delete_list 中我传递了"*.sh"

从文件中删除字符串应该传递给我的 delete_list 以从文件中删除字符串值。

test.py

#!/usr/bin/env python3
import sys

infile = "input_file"
outfile = "expected_file"

delete_list = ["*.sh"]
with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        for word in delete_list:
            line = line.replace(word, "")
        fout.write(line)

输入文件

papaya.sh   10
Moosumbi.sh 44
jackfruit.sh 15
orange.sh 11
banana.sh 99
grapes.sh 21
dates.sh 6

expected_file

10
44
15
11
99
21
6

【问题讨论】:

  • 问题真的是要删除一组字符串,还是问题真的只是“打印第二列”?这是一个简单得多的问题,甚至可能不需要 Python。
  • @TimRoberts 打印第二列也可以。但我试图使用 python 消除字符串

标签: python string list file


【解决方案1】:

使用正则表达式可能是要走的路。这是一种类似于您编写的方法 - 我们假设 input.txt 包含您的输入值,output.txt 作为导出文件:

#!/usr/bin/env python3
import re

infile = "input.txt"
outfile = "output.txt"
delete_list = [r'^.+\.sh\s*']

with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        for word in delete_list:
            line = re.sub(word, "", line)
            fout.write(line)

【讨论】:

    【解决方案2】:

    您可以使用regular expressions

    import re
    from io import StringIO
    
    pattern = re.compile(r'^.+\.sh\s*')
    
    data = '''\
    papaya.sh   10
    Moosumbi.sh 44
    jackfruit.sh 15
    orange.sh 11
    banana.sh 99
    grapes.sh 21
    dates.sh 6
    '''
    
    # replace these two with your open(...) calls
    fin = StringIO(data)
    fout = StringIO()
    
    for line in fin:
        fout.write(pattern.sub('', line))
    
    # just for demonstration
    print(fout.getvalue())
    

    【讨论】:

    • 我不会知道字符串数据的内容。只有我会知道字符串内容将以 .sh 结尾
    • 如代码中的注释中所述,您应该将StringIO(data) 替换为您的open(infile)。你肯定没想到我会在我的机器上为你创建几个文件。
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 2013-11-02
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多