首页 > 解决方案 > RegEx 字符串在 Python 中直接分配时有效,但不是从 PostgreSQL 数据库中分配

问题描述

我有一个工作例程来确定新闻项目所属的类别。该例程在 Python 中为标题、类别、子类别和作为 RegExp 的搜索词分配值时起作用。

但是,当从 PostgreSQL 检索这些值作为字符串时,我没有收到任何错误,或者来自同一例程的结果。

我检查了数据类型,它们都是 Python 字符串。

可以做些什么来解决这个问题?

# 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)

标签: pythonregexpostgresql

解决方案


我很确定你从 PostgreSQL 得到的不是原始字符串文字,因此你的 RegEx 是无效的。您必须在数据库中明确地转义模式中的反斜杠。

print(r"\basm\b")
print("\basm\b")
print("\\basm\\b")

# output
\basm\b

as       # yes, including the line break above here
\basm\b

推荐阅读