我创建了一个函数来搜索NLTK.text.text对象,并在运行函数时返回一个值。在
更新:问题似乎是在下面的函数中,'dongion'变量实际上没有被传递一个值。这个文本.findall但是,函数确实返回一个值,但由于某些原因不更新变量。在
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而不是实际的“回赠”。在
^{pr2}$输出=
Mr. T 's Tea Party
the Boys and Girls club
但是,当我尝试应用该函数以将输出写入pandas数据框中的新列时,它返回的是None。见下文:
df['donation_orgs'] = df.apply(lambda row: find_donation_orgs(row['Obit']), axis = 1)
其中df['Obit']是一个文本字符串,类似于上面的my a变量。在
更新:所以看起来文本.findall不更新其分配给的变量的值。。。所以我需要弄清楚如何将输出分配给一个变量,以便将它返回到一个数据帧。见下文:
text = df.text.iloc[1]
textfindall = text.findall(r"<\.> <.*>{,15}? <donat.*|contrib.*|Donat.*|Contrib.*> <.*>*? <to> (<.*>+?) <\.|\,|\;> ")
print('text is ' + str(type(text)))
print('textfindall is ' + str(type(textfindall)))
print(textfindall)
输出:
visit brother Alfred Fuller; the research of Dr. Giuseppe Giaccone at
Georgetown University
text is <class 'nltk.text.Text'>
textfindall is <class 'NoneType'>
none
尝试通过检查函数实际接收和返回的内容来调试代码。您可以使用调试器(在大多数IDE中都可以找到),也可以使用函数的返回值来确定问题是出在函数还是熊猫函数上
确保您的输入符合您的期望。在
^{pr2}$看看标记化是怎么回事。在
检查你的正则表达式是否有问题。在这种情况下,返回tokenizer输出,尝试修复正则表达式。在
更新
查看source code of the ^{} 对象,
^{4}$findall
方法实际上并不返回任何内容,而是打印结果:这是因为
Text
对象仅用于交互式控制台:您的功能应该如下所示:
这将复制原始行为,但实际返回值除外。当然,在收到
hits
列表后,您可能希望以不同的方式格式化输出。在相关问题 更多 >
编程相关推荐