[英]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.