【问题标题】:How to trim text from file and put it another file using python?如何使用 python 修剪文件中的文本并将其放入另一个文件?
【发布时间】:2023-02-03 22:46:39
【问题描述】:

我有一个名为 file1 的文本文件


    
        HelloWorldTestClass
        MyTestClass2
        MyTestClass4
        MyHelloWorld        
        ApexClass
    
    
        *
        ApexTrigger
    
    
        Book__c
        CustomObject
    
    56.0

现在我想输出我的文件,如 file2 中包含 test 的单词,并有这样的输出

        HelloWorldTestClass
        MyTestClass2
        MyTestClass4

我有这样的代码

import re
import os

file_contents1 = f'{os.getcwd()}/build/testlist.txt'
file2_path = f'{os.getcwd()}/build/optestlist.txt'
with open(file_contents1, 'r') as file1:
    
    file1_contents = file1.read()
   
# print(file1_contents)

# output = [file1_contents.strip() for line in file1_contents if "TestClass" in line]
# # Use a regudjlar expression pattern to match strings that contain "test"
test_strings = [x for x in file1_contents.split("\n") if re.search(r"test", x, re.IGNORECASE)]
# x = test_strings.strip("['t]")
# # Print the result
with open(file2_path, 'w') as file2:
    # write the contents of the first file to the second file
    for test in test_strings:
        file2.write(test)


但它正在输出 HelloWorldTestClass MyTestClass2 MyTestClass4

我没有找到相关问题,如果已经问过,请附上,谢谢

【问题讨论】:

  • 这是非常少的信息。您到底想复制什么,名称或相关代码?您只想复制名称中带有“Class”的类或类吗?
  • 解释你的切割逻辑,为什么只有3条记录?
  • 我已经编辑了问题,请查看,抱歉给您带来麻烦
  • 您希望file2 中的输出与file1 中的制表符数量相同吗?
  • 不,我想提取包含test的单词并像上面一样打印出来file2

标签: python


【解决方案1】:

您可以使用带有字符串的 in 运算符来检查它是否包含您的短语:

with open('file1.txt', "r") as f_input:
    with open('file2.txt', "w") as f_output:
        for line in f_input:
            if "test" in line.lower():
                f_output.write(line)

【讨论】:

    猜你喜欢
    • 2019-08-20
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多