python正则表达式统计字符串的个数

目的:通过python将pubmed下载的摘要txt文档,统计出其中的PMID数目,是否和文献总篇数一致,一致的话,就可以利用PMID的regex pattern进行分割字符串为单篇摘要文献。

import re

fname = '2020-01-14_endometriosis_2020-01-01_UTF8.txt'
with open(fname, "r", encoding = 'utf-8') as f:
    abstracts = f.read()

str = abstracts
iList= re.findall(r"PMID: d+ ",str)
print(len(iList)) # output: 6049,符合文档中文献的总篇数

iList= re.findall(r"PMID: d+",str) # regex pattern中少一个空格
print(len(iList)) # output: 6050,结果比文档中文献总篇数多了一篇
原文地址:https://www.cnblogs.com/songbiao/p/12299991.html