我正在尝试从文本文件中提取某些数据字符串。 我使用的代码如下。我想从该文本文件中读取特定的字符串(所有操作),然后将其存储在数组或列表中(如果找到)。然后以相同的顺序显示。
import string
solution_path = "/homer/my_dir/solution_detail.txt"
solution = open(solution_path).read()
all_actions = ['company_name','email_address','full_name']
n = 0
sequence_array = []
for line in solution:
for action in all_actions:
if action in line:
sequence_array[n] = action
n = n+1
for x in range(len(sequence_array)):
print (sequence_array[x])
但是这段代码除了执行没有任何错误外,什么也不做。
What is happening is that
solution
contains all the text inside the file. Therefore when you are iteratingfor line in solution
you are actually iterating over each and every character separately, which is why you never get any hits.尝试以下代码(由于没有文件,我无法对其进行测试)
这将收集文档中的所有操作。如果要打印所有这些