如何解决sre_constants.error:对于特殊情况* CLK *,在位置0上无需重复

时间:2018-09-26 12:57:36

标签: python pandas

我有一个熊猫数据框

import pandas as pd
df = pd.read_csv("MyCsv.csv", delimiter='@@@')
df
    ID  Signal
0   0   HT_CLKIN_P
1   1   HT_CLKOUT_P
2   2   LDTPHY013_Inst1.HT_REFCLK
3   3   clk_PCI1CLK_H
4   4   clk_ht100_or_200_H
5   5   clk_pcibr66_H
6   6   h_extrxclkin
7   7   h_exttxclkin

def filterData(df,colname,regex):
'''
df:: Dataframe Name
colname: Name of the column against which you want to filter the data.
regex: Regular expression or special characters you want to search.
'''
return df[df[colname].str.contains(regex,regex=True)]

filterData(df,'Signal','clk_ht100*')

filterData(df,'Signal','*CLK*')

我遇到以下错误

---------------------------------------------------------------------------
  error                                     Traceback (most recent call 

   last)
    <ipython-input-9-32fc02914557> in <module>()
   ---->    1 filterData(df,'Signal','*CLK*')

   <ipython-input-8-aeebba3ee8c6> in filterData(df, colname, regex)
      5     regex: Regular expression or special characters you want to search.
        6     '''
        ----> 7     return df[df[colname].str.contains(regex,regex=True)]

        ~\AppData\Local\Continuum\anaconda3\lib\site- 
        packages\pandas\core\strings.py in contains(self, pat, case, flags, na, regex)
         1565     def contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
         1566         result = str_contains(self._data, pat, case=case, flags=flags, na=na,
        -> 1567                               regex=regex)
          1568         return self._wrap_result(result)
           1569 

           ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\strings.py in str_contains(arr, pat, case, flags, na, regex)
        247             flags |= re.IGNORECASE
        248 
     --> 249         regex = re.compile(pat, flags=flags)
        250 
        251         if regex.groups > 0:

        ~\AppData\Local\Continuum\anaconda3\lib\re.py in compile(pattern, flags)
         231 def compile(pattern, flags=0):
         232     "Compile a regular expression pattern, returning a pattern object."
    -->   233     return _compile(pattern, flags)
          234 
          235 def purge():

         ~\AppData\Local\Continuum\anaconda3\lib\re.py in _compile(pattern, flags)
    299     if not sre_compile.isstring(pattern):
    300         raise TypeError("first argument must be string or compiled pattern")
      --> 301     p = sre_compile.compile(pattern, flags)
          302     if not (flags & DEBUG):
          303         if len(_cache) >= _MAXCACHE:

          ~\AppData\Local\Continuum\anaconda3\lib\sre_compile.py in compile(p, flags)
        560     if isstring(p):
        561         pattern = p
         -->       562         p = sre_parse.parse(p, flags)
           563     else:
           564         pattern = None

         ~\AppData\Local\Continuum\anaconda3\lib\sre_parse.py in parse(str, flags, pattern)
         853 
         854     try:
          -->      855         p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
         856     except Verbose:
         857         # the VERBOSE flag was switched on inside the pattern.  to be

            ~\AppData\Local\Continuum\anaconda3\lib\sre_parse.py in _parse_sub(source, state,   verbose, nested)
              414     while True:
               415         itemsappend(_parse(source, state, verbose, nested + 1,
         -->     416                            not nested and not items))
                 417         if not sourcematch("|"):
                 418             break

             ~\AppData\Local\Continuum\anaconda3\lib\sre_parse.py in _parse(source, state, verbose, nested, first)
              614             if not item or (_len(item) == 1 and item[0][0] is AT):
               615                 raise source.error("nothing to repeat",
               -->            616                                    source.tell() - here + len(this))
            617             if item[0][0] in _REPEATCODES:
            618                 raise source.error("multiple repeat",

           error: nothing to repeat at position 0

1 个答案:

答案 0 :(得分:0)

在正则表达式中,*是一个量词,表示前面的模式应匹配零次或更多次。由于正则表达式格式错误,将引发错误nothing to repeat at position 0。量词不能应用于任何模式,因为没有适用于它的模式。我建议您阅读正则表达式的一些基础知识。 Python re模块已记录在here中。

您可能想要的是这些表达式:

filterData(df,'Signal','clk_ht100.*')
filterData(df,'Signal','.*CLK.*')

通过字符串匹配也可以实现相同的功能,并且不需要正则表达式:

>>> df['Signal'].str.startswith("clk_ht100")
0    False
1    False
2    False
3    False
4     True
5    False
6    False
7    False
Name: Signal, dtype: bool

>>> df['Signal'].str.contains("CLK")
0     True
1     True
2     True
3     True
4    False
5    False
6    False
7    False
Name: Signal, dtype: bool

您可以在Working with Text Data文档的底部找到可用的字符串方法的列表。