【问题标题】:Add punctuation at the end of sentence after regular expression processing: Python正则表达式处理后在句尾添加标点:Python
【发布时间】:2021-08-03 08:44:15
【问题描述】:

我正在尝试为基于方面的情感分析做一些模式匹配常规回归问题。模式匹配后,我无法处理正确位置的标点符号。

def extra_expression1(txt):
  txt= str(txt)
  nlp=spacy.load("en_core_web_sm") 
  txt=nlp(txt)
  punc=''
  a=len(txt)
  for token in txt:
    if (token.is_punct==False):
      txt=str(txt)
      txt=re.sub('goo+d+[^a-z]','good',txt) #"goooodddd" to "good"
      a=a-1
    else:
      punc=token.text
      if (a!=0):
        txt=str(txt) + str(punc)
        punc=''
      else:
        txt=str(txt) + str(punc)
      a=a-1
  return txt

txt1=["hotel is goood! breakfast was bad."]
df_22=pd.DataFrame(
    {
        'clean_review' : txt1
    }
)
display(df_22)

for i,txt in enumerate(df_22['clean_review']):
  txt1= extra_expression1(txt)
  df_22['clean_review'].iloc[i]=txt1
df_22

输出是(处理后的最后一个):

我该如何解决这个问题?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    无法运行您的代码,但good 后面的字符不应该是匹配的一部分。尝试使用前瞻:

    txt=re.sub('goo+d+(?=[^a-z])','good',txt) #"goooodddd" to "good"
    

    【讨论】:

    • 谢谢。有效。你能告诉我这个“(?=[^a-z])”的详细含义吗?这将有助于我轻松理解。我只知道这个 [^a-z] 部分。
    • 前瞻是零长度的断言。这意味着他们不会为比赛消耗字符。它允许您在后面的(或后面的)字符上设置条件,而不会将它们作为匹配的一部分。查看此链接:regular-expressions.info/lookaround.html 或者更容易阅读:rexegg.com/regex-lookarounds.html
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2016-12-22
    • 2012-03-01
    相关资源
    最近更新 更多