I have a list1 = ['hi','world','of']
I have a.txt file
Hellohihowareyou
worldisfullofwonder
How to check whether hi
, 'of'
, and world
exists in the file
pseudo code
import re
pattern = r''
for i in list1:
#print (i)
with open('file.txt','r'):
content = f.read()
test= re.search(pattern,content)
print (test)
My Expected out ['hi','of']
, since there is no world in the file
You can also do it with in
keywords, use regex if your pattern start to be more advanced.
list1 = ['hi','world','of']
text = """ Hellohihowareyou
worldisfullofwonder"""
results = []
for element in list1:
if element in text:
results.append(element)
print(results)
results = [element for element in list1 if element in text]
print(results)
use this:
import re
file = 'file.txt'
content = ''
lst = ['hi','world','of']
with open(file, 'r') as file_handler:
content = file_handler.read()
result = re.findall('|'.join(lst), content)
import re
file = r'C:\Users\wind\Desktop\file.txt'
list1 = ['hi','of','wonderw']
pattern = r''
for i in list1:
pattern = re.compile(i, re.IGNORECASE)
with open(file,'r') as f:
content = f.read()
test= re.search(pattern,content)
print (test)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.