python中正则表达式代码中的错误
我正在做一个家庭作业,我需要使用正则表达式在另一个更大的名为lorem_ipsum的字符串中查找各种字符和字符串,我不断得到TypeError:预期的字符串或缓冲区,指定lorem_ipsum是一个字符串而不是列表,所以这不是问题所在。 以下是我编写的两段代码: 这是查找lorem_ipsum中的所有非字母数字字符,并输出它们出现的次数,它应返回144:python中正则表达式代码中的错误,python,regex,Python,Regex,我正在做一个家庭作业,我需要使用正则表达式在另一个更大的名为lorem_ipsum的字符串中查找各种字符和字符串,我不断得到TypeError:预期的字符串或缓冲区,指定lorem_ipsum是一个字符串而不是列表,所以这不是问题所在。 以下是我编写的两段代码: 这是查找lorem_ipsum中的所有非字母数字字符,并输出它们出现的次数,它应返回144: string1 = len(lorem_ipsum) pattern = "^[[]]" matches1 = re.match(patter
string1 = len(lorem_ipsum)
pattern = "^[[]]"
matches1 = re.match(pattern, string1)
results = matches1.read()
这一个是找到lorem_ipsum中所有发生的sit ament,并输出它们发生的次数,它应该输出3:
string1 = len(lorem_ipsum)
pattern = "sit[-:]amet"
matches1 = re.findall(pattern, string1)
results = matches1.count(pattern, string1)
print (results)
我以前从未遇到过这个问题,据我所知,我使用的语法与以前的作业相同。您的问题是代码第2行中的
len()
左右lorem\u ipsum
len()。拆下透镜,使第2行看起来像这样:
matches1=re.match(pattern,lorem_ipsum)
。尝试将第一个模式改为使用[[]]
(假设您尝试匹配[
或]
)。您应该匹配字符串,而不是len。这里是len(lorem_ipsum))
。我刚刚尝试了[],但没有成功,我将在预期输出中进行编辑。为什么您要匹配int(len)呢?我刚刚更改了,我将编辑它。如果您编辑了代码,您将删除第一行中的len