【发布时间】:2015-12-04 17:11:49
【问题描述】:
我创建了一个搜索 NLTK.text.Text 对象的函数,并在我运行该函数时返回一个值。
更新:问题似乎是在下面的函数中,“捐赠”变量实际上并没有被传递一个值。然而,text.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
以下输入的输出类似于此,但我认为输出来自 text.findall 而不是实际的“回报捐赠”。
a = "This is a sentence. I also donate to Mr. T's Tea Party. I contribute to the Boys and Girls club. "
find_donation_orgs(a)
输出 =
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'] 是一串文本,类似于我上面的 a 变量。
更新:所以看起来 text.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
【问题讨论】:
-
df['donation_orgs'] = df['Obit'].apply(lambda x: find_donation_orgs(x), axis=1)? -
该代码运行良好,并且确实创建了一个“donation_orgs”列,但仍然在该列的每一行中返回 None ......我认为这是我的函数总是返回 none 类型的某种问题对象,即使 text.findall 工作正常
标签: python pandas nlp dataframe nltk