我想在python 3中搜索文本文件中的列表元素
我想在文本文件中搜索列表元素 首先,我在variables.txt文件中搜索了我想在python 3中搜索文本文件中的列表元素,python,list,search,element,Python,List,Search,Element,我想在文本文件中搜索列表元素 首先,我在variables.txt文件中搜索了HELP,并将其存储在lista中, 这是['setpoint\u code\u help;'、'position\u code\u help;'、'torque\u code\u help;'] 现在,我试图在labels.h文件中搜索该列表a中的元素,但在labels.h文件中找不到该元素 labels.h包含如下文本: #define setpoint_code_help "En
HELP
,并将其存储在lista
中,
这是['setpoint\u code\u help;'、'position\u code\u help;'、'torque\u code\u 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:\\HelpString\\6060E28C0101VAlabels.h',“r+”)作为文件1:
fileline1=file1.readlines()
对于d中的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']
d首先是空列表,将不会得到inside@Aaron_ab:这是代码的第二部分。OP将数据附加到d
中,这样它就不再是空的了。@Bazingaa:我尝试过你的解决方案,但是“如果x在行中:”不起作用。@DeeptiKhanvilkar:你能试试如果x在行中。split():
并告诉我它是否起作用吗?我按照你的建议更新了我的代码:使用open('D:\\HelpString\\6060E28C0101VAlabels.h',“r+”)作为文件1:fileline1=file1.readlines(),用于D中的x:fileline1:if x in line.split():print('true')其他:print('False'))我得到的结果是“假”是的,你所理解的是正确的!我会尝试你的建议并让你知道结果。@DeeptiKhanvilkar-如果答案解决了你的问题,你能分享一下吗?