【问题标题】:Error using regex. Assertion error : Got <class 'str'>, expected <class 'list'>`使用正则表达式时出错。断言错误:得到 <class 'str'>,预期 <class 'list'>`
【发布时间】:2019-01-24 21:02:11
【问题描述】:

我正在尝试使用正则表达式实现一个函数来删除标签并返回文本文件中找到的字符串列表。但是,出现以下错误:

AssertionError: Wrong type for output extracted_words. Got &lt;class 'str'&gt;, expected &lt;class 'list'&gt;

这是我下面的代码,我们将不胜感激。

import re

def get_words(text):
    """
    Extracting words from the text

    The 'text' parameter is the file which contains strings inside

    Objective: To return a list of strings found in the text called 'extracted_words'
    """
    # Implementation
    extracted_words = re.sub('<[^>]*>', '', text)
    return extracted_words

【问题讨论】:

  • 无法复制。请提供minimal reproducible example。相关的assert 语句也很有用。
  • re.sub 不会返回列表,因为它的工作方式类似于 str.replace。你的意思是使用re.match
  • 当我尝试时,我得到了。 'TypeError: unsupported operand type(s) for &amp;: 'str' and 'int'@NChauhan

标签: python regex nlp


【解决方案1】:

这对我有用:

rgxp = re.compile(r'([^<>]+)(?=<)')
return re.findall(rgxp, text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多