Py学习  »  Python

Python中使用缩写的正则表达式

Gianni Spear • 3 年前 • 1228 次点击  

我有几千行,比如:

“序列1,-2,-1,2,1,-2,-1,2,…,和g.f.(1-2x)/(1+x^2)有一个(n)=cos(Pi*n/2)-2*sin(Pi*n/2)- 保罗·巴里 ,2004年10月18日“

我需要找到日期的位置,如果有的话,比如“03年8月”。为此,我写了一个函数 _find_all_positions

def _add_zero(value: int) -> str:
   """add zero to number with digits < 2"""
   value_str = str(value)
   digits = len(value_str)
   if digits < 2:
       value_str = '0' + value_str
   return value_str
    
def get_date() -> list:
    """Get dates for author(s) search, from ' Jan 01' to ' Dec 31' """
    dates = list()
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    for month in months:
        for day in range(1, 32):
            dates.append(' ' + month + ' ' + ParserUtilities._add_zero(day))
    return dates

def _find_all_positions(string: str, sub: str):
    """Find all occurrences of a substring in a string"""
    start = 0
    while True:
        start = string.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)  # use start += 1 to find overlapping matches

这项任务很慢,我想知道你是否同意 Regular Expression 有可能加快搜索速度

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133030
 
1228 次点击  
文章 [ 2 ]  |  最新文章 3 年前