正则表达式字符串在Python中直接赋值时有效,但不能从PostgreSQL数据库中赋值
我有一个工作程序来确定新闻项目所属的类别。在Python中将标题、类别、子类别和搜索词的值指定为RegExp时,该例程起作用 但是当从PostgreSQL中以字符串形式检索这些值时,我没有得到任何错误,也没有得到来自同一例程的结果 我检查了数据类型,它们都是Python字符串 如何解决这个问题正则表达式字符串在Python中直接赋值时有效,但不能从PostgreSQL数据库中赋值,python,regex,postgresql,Python,Regex,Postgresql,我有一个工作程序来确定新闻项目所属的类别。在Python中将标题、类别、子类别和搜索词的值指定为RegExp时,该例程起作用 但是当从PostgreSQL中以字符串形式检索这些值时,我没有得到任何错误,也没有得到来自同一例程的结果 我检查了数据类型,它们都是Python字符串 如何解决这个问题 # set the text to be analyzed title = "next week there will be a presentation. The location will be aa
# set the text to be analyzed
title = "next week there will be a presentation. The location will be aat"
# these could be the categories
category = "presentation"
subcategory = "scientific"
# these are the regular expressions
main_category_search_words = r'\bpresentation\b'
sub_category_search_words= r'\basm microbe\b | \basco\b | \baat\b'
category_final = ''
subcategory_final = ''
# identify main category
r = re.compile(main_category_search_words, flags=re.I | re.X)
result = r.findall(title)
if len(result) == 1:
category_final = category
# identify sub category
r2 = re.compile(sub_category_search_words, flags=re.I | re.X)
result2 = r2.findall(title)
if len(result2) > 0:
subcategory_final = subcategory
print("analysis result:", category_final, subcategory_final)
我敢肯定,您从PostgreSQL得到的不是一个,因此您的正则表达式是无效的。您必须在DB中显式地转义模式中的反斜杠
print(r"\basm\b")
print("\basm\b")
print("\\basm\\b")
# output
\basm\b
as # yes, including the line break above here
\basm\b
谢谢,这肯定会让你明白应该纠正什么!。作为测试,我将PostgreSQL中的DB main category条目更改为\\b表示\\b,然后r=re.compiler'+main_category_search_words+',flags=re.I|re.X,但没有结果。我想我很接近,但不确定从这里开始。建议是非常受欢迎的!:您可以打印编译后的表达式,以验证它是否是您要查找的表达式。在我看来,由于字符串连接,您现在似乎以“\bams\b”结束,包括单引号。我不认为连接是必要的,因为你已经改变了DB值。Shmee谢谢你把我推向了正确的方向,现在它工作了!我只想向未来的任何人指出这一挑战。为了从PostgreSQL将原始字符串转换成Python,我使用了r+search_单词,因为没有它,字符串就不会被视为原始字符串:r=re.compiler+main_category_search_单词,flags=re.i | re.X