python - 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)
解决方案
我很确定你从 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
推荐阅读
- java - 在sql查询中使用变量作为列
- android - 快捷方式创建不起作用
- asterisk - 在 pjsip max_calls 上调用限制为 32 次调用
- mysql - nodejs中的一些代码让我感到困惑
- html - 阻止动画在 CSS 中自动播放
- c - 使用带有文件扩展名 .r 的自动工具作为标题,而不是 ratfor 而是 C 编程
- python - NLTK 错误:OSError:没有这样的文件或目录
- jquery - 如何使用 jQuery 对动态数组进行排序?
- r - 将 auto.arima() 映射到子集时间序列列表
- python - 查找元素值是唯一的,并且列表中的所有元素都相同