【问题标题】:Searching for number of repeated patterns in text file using Python使用 Python 在文本文件中搜索重复模式的数量
【发布时间】:2021-02-27 05:29:40
【问题描述】:

我想知道有关可用于输出文本文件中找到的模式数量的代码的任何建议。

示例:我有一个带有 ("ABBAABBBAAABAB") 的文本文件,我想搜索特定的模式,例如 ("ABA"),但我不希望它把最后一个字母计为模式的一部分,只计算新字母。

我尝试过使用split()count(),但它似乎给了我在每一行而不是整个文件上找到的数字,当我不使用split() 将其放入列表时,它只会打印0。

例如它给我这个:

0
0
0
0
0 

当拆分它时,它有点工作,但不只给我每一行的总和,例如:

23
32
12
20
15

我怎样才能得到我在整个文件中搜索的模式的总和,只有一个数字,比如 150 等......

非常感谢您的帮助,谢谢

【问题讨论】:

  • 请贴出你的代码sn-p
  • but I dont want it to count the last letter as part of the pattern, only new letters看不懂,能详细点吗?
  • 你能举个例子来说明你想要的输出吗

标签: python python-3.x regex numpy python-requests


【解决方案1】:
import re
input_text = 'ABBAABBBAAABAB'
pattern = 'ABA'
# removing last letter
input_text = input_text[:-1]
result = len([*re.finditer(pattern, input_text)])

结果将具有所需的计数。

【讨论】:

    【解决方案2】:
     import re
     data="ABBAABBBAAABABABA"
     matches=re.finditer(r"(ABA)+",data)
     for match in matches:
          print(match)
    

    输出:

     <re.Match object; span=(10, 13), match='ABA'>
     <re.Match object; span=(14, 17), match='ABA'>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多