【发布时间】: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