gpt4 book ai didi

python - 从python中的unicode(外语)段落中提取主题标签

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:18 25 4
gpt4 key购买 nike

我正在尝试开发一个从段落中提取主题标签的函数,基本上是以#开头的单词 (#cool #life #cars #سيارات)

我已经尝试了几种方法,例如使用 split() 和使用正则表达式,但没有尝试包含阿拉伯语、俄语等的 unicode 字符。

我尝试使用 split() 效果很好,但它会包含任何单词,在我的情况下,我不能包含带有特殊字符的单词,例如 ,.%$]{ }{)(.. 还尝试包括一些验证,例如字长不超过 15 个字符。

我试过这种方法 -

def _strip_hash_tags(self, ):
"""tags should not be more than 15 characters"""
hash_tags = re.compile(r'(?i)(?<=\#)\w+')
return [i for i in hash_tags.findall(self.content) if len(i) < 15]

这仅适用于英语,不适用于外语。有什么建议吗?

最佳答案

正如此处讨论的那样 - python regular expression with utf8 issue .

First you should use re.compile(ur'<unicode string>'). Also it is nice to add re.UNICODE flag (not sure if really needed here though).

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re


def strip_hash_tags(content):
"""tags should not be more than 15 characters"""
hash_tags = re.compile(ur'(?i)(?<=\#)\w+',re.UNICODE)
return [i for i in hash_tags.findall(content) if len(i) < 15]

str = u"am trying to work on a function to extract hashtags from paragraphs, basically words that starts with # (#cool #life #cars #سيارات)"

print(strip_hash_tags(str))

# [u'cool', u'life', u'cars', u'\xd8\xb3\xd9']

关于python - 从python中的unicode(外语)段落中提取主题标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18250593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com