【问题标题】:How to match the list item to content in the file如何将列表项与文件中的内容匹配
【发布时间】:2019-10-21 13:20:30
【问题描述】:

我有一个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'],因为文件中没有世界

【问题讨论】:

  • 为什么是正则表达式?您在这里似乎不需要整个单词或不区分大小写的匹配。只需检查for i in list1: if i in content: results.append(i)
  • 这句好话“你有问题,但认为你可以用正则表达式解决它。现在你有两个问题”在这里适用。

标签: python regex file


【解决方案1】:

您也可以使用in 关键字来实现,如果您的模式开始更高级,请使用正则表达式。

正常

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)

【讨论】:

    【解决方案2】:

    使用这个:

    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)
    

    【讨论】:

      【解决方案3】:
      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        相关资源
        最近更新 更多