簡體   English   中英

我想在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文件中找到該元素。

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM