[英]How to make combination of a string using list of words for each position
[英]Search each line list in a file that contain combination of specific words/string
我正在尝试从文件的每一行中搜索特定的单词,如果发现这些单词会做一些事情。
例如,我有一个包含名称列表的文件
pSet02Hw codeid xxxxx
Set01Mt codeid xxxxx
Set02Mt codeid xxxxx
pSet03Hw codeid xxxxx
pSet07Hw codeid xxxxx
pset01hw codeid xxxxx
set03mt codeid xxxxx
我读了文件中的每一行。 从文件中,我想搜索设置和 hw 的行而不是执行 process1 和 elif 行设置和 mt 而不是执行 process2。 除非我只搜索 set ,否则下面的代码无法正常工作,但这可能会导致执行错误的进程。
if 'sethw' in linelist[0]:
execute process1
elif 'setmt' in linelist[0]:
execute process2
else:
print("No process executed")
break
我尝试了“set”和“hw”的组合以及“set”和“mt”的组合,但它不能正常工作。
请建议并告诉我正确的做法。 谢谢你们。
通过在这个上使用 RegEx,你会做得很好。 下面的示例代码:
import re
pattern1 = re.compile(r'^pset\d{2}hw', re.IGNORECASE)
pattern2 = re.compile(r'^set\d{2}mt', re.IGNORECASE)
# Assuming your linelist is already subdivided into list of lists:
for line in linelist:
if re.search(pattern1, line[0]):
# execute process 1
elif re.search(pattern2, line[0]):
# execute process 2
上面的正则表达式模式更多的是指导,但可以根据自己的喜好进行调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.