.findall正则表达式不会分配给变量

2024-09-30 08:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数来搜索nltk.text.text输入和输出“贡献”或“捐赠”后面的所有单词(参见下面的正则表达式)。在

正则表达式工作得很好,但是当我试图将它赋给一个变量以便函数返回它时,变量不会更新,我的函数也不会返回任何结果。在

即类型(捐赠)=非类型对象

我最终希望将此函数应用于数据帧的每一行,并将捐赠值输出到该数据帧中的新列,但当我现在尝试时,每个输出都是“None”

def find_donation_orgs(x):
    text = nltk.Text(nltk.word_tokenize(x))
    donation =  text.findall(r"<\.> <.*>{,15}? <donat.*|contrib.*|Donat.*|Contrib.*> <.*>*? <to> (<.*>+?) <\.|\,|\;> ")
    return donation

我的findall regex本身可以工作:

^{pr2}$

返回以下文本示例:

visit brother Alfred Fuller; the research of Dr. Giuseppe Giaccone at
Georgetown University

为了您的利益:

text = nltk.Text(nltk.word_tokenize(df.Obit.iloc[7]))
print(text)

x = text.findall(r"<\.> <.*>{,15}? <donat.*|contrib.*|Donat.*|Contrib.*> <.*>*? <to> (<.*>+?) <\.|\,|\;> ")

print(x)

退货:

<Text: M. Jay Janssen , age 95 of Zeeland...>
Resthaven Care Community
None

Tags: 数据函数textnone类型donationcontribword
1条回答
网友
1楼 · 发布于 2024-09-30 08:23:49

正如R Nar在上面提到的,findall regex只打印,不返回任何内容。。。令牌搜索器完美地解决了这个问题。。。它确实输出一个令牌列表,而不是一个字符串,但是它完成了任务。在

from nltk.text import TokenSearcher

def find_donation_orgs(x):
    text = nltk.Text(nltk.word_tokenize(x))
    donation = TokenSearcher(text).findall(r"<\.> <.*>{,15}? <donat.*|contrib.*|Donat.*|Contrib.*> <.*>*? <to> (<.*>+?) <\.|\,|\;> ")
    return donation

相关问题 更多 >

    热门问题