Python 如何将列表项与文件中的内容相匹配
我有一个Python 如何将列表项与文件中的内容相匹配,python,regex,file,Python,Regex,File,我有一个list1=['hi','world','of'] 我有一个.txt文件 Hellohihowareyou worldisfullofwonder 如何检查文件中是否存在hi、'of'和world 伪码 import re pattern = r'' for i in list1: #print (i) with open('file.txt','r'): content = f.read() test= re.search(pattern,conten
list1=['hi','world','of']
我有一个.txt文件
Hellohihowareyou
worldisfullofwonder
如何检查文件中是否存在hi
、'of'
和world
伪码
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)
我的预期出局了
['hi','of']
,由于文件中没有世界您也可以在关键字中使用,如果您的模式开始更高级,请使用regex
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)
正常的
list1=['hi','world','of']
text=“”你好,你好吗
“世界充满了风”
结果=[]
对于列表1中的元素:
如果文本中有元素:
results.append(元素)
打印(结果)
列表理解
results=[列表1中的元素对应于文本中的元素]
打印(结果)
使用以下方法:
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)
为什么是正则表达式?在这里,您似乎不需要完整的单词或不区分大小写的匹配。只需检查列表1中的i:if i in content:results.append(i)
“你有问题,但认为你可以用正则表达式解决它。现在你有两个问题”这句谚语适用于这里。