我想在 python 3 中的文本文件中搜索列表元素

I want to search list element in the text file in python 3

我想在文本文件中搜索列表元素。

首先,我在 variables.txt 文件中搜索 HELP,我将其存储在列表 a 中, 这是 ['setpoint_code_help;', 'position_code_help;', 'torque_code_help;'] 现在,我正在尝试从 labels.h 文件中的列表 a 中搜索元素,但我无法在 labels.h 文件中找到该元素。

labels.h 包含如下文本:

#define setpoint_code_help                  "Enable or Disable the alarms of Setpoint"
#define position_code_help                  "Enable or Disable the alarms of Position"
#define torque_code_help                    "Enable or Disable the alarms of Torque"

我需要获取那些帮助的定义。 请让我知道您对此的评论。

d=[]

with open('D:\HelpString\variables.txt',"r+") as file:
    fileline= file.readlines()

    for x in fileline:
        if x.find('VARIABLE')>0:
            #a.append(x)
            print(x)
        elif x.find('HELP')>0:
            a=x.split()
            d.append(a[1])
            #print(type(c))
    print(d)
with open('D:\HelpString\6060E28C0101VAlabels.h', "r+") as file1:
    fileline1= file1.readlines()
    for x in d:       
        if x in fileline1:
             print(x)

您需要在此处嵌套 for 循环:一个循环遍历要检查的列表项,另一个循环遍历文件的行。你可以做类似

with open('D:\HelpString\6060E28C0101VAlabels.h', "r+") as file1:
    fileline1= file1.readlines()
    for x in d: # <--- Loop through the list to check      
        for line in fileline1: # <--- Loop through each line
            if x in line:
                 print(x)

据我了解,在读取第一个文件后,您有一个名为 d 的列表,其中包含一些字符串。

你想要的是读取第二个文件,并仅过滤包含来自 d 的字符串的行,对吧?

是这样,问题就变成了过滤一个字符串列表,其中有一些字符串来自另一个列表(d)

可以做到:

# second file, after building the "d" list    

def filter_lines_by_keywords(lines_to_filter, key_words):
   key_words_s = set(key_words)
   return filter(lambda l: set(l.split()) & key_words_s, lines_to_filter)


with open('D:\HelpString\6060E28C0101VAlabels.h', "r+") as file1:
    file1lines = file1.readlines()

filtered_lines = filter_lines_by_keywords(file1lines, d)

运行 示例:

d = ['word1', 'word2']
file1lines = ['line1 has some words', 
              'line2 has word1 and other', 
              'line3 has word2 and word1', 
              'line4 had nothing']
res = filter_lines_by_keywords(lines_to_filter = file1lines, 
                              key_words = d)

print(list(res))
>> ['line2 has word1 and other', 'line3 has word2 and word1']