python - 在 Python 中标记一个句子并重新连接结果
问题描述
我遇到了一个问题,我正在寻求帮助,我确实有以下代码:
import nltk
import pandas as pd
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
d = {'col1': ['AI is our friend and it has been friendly', 'AI and human have always been friendly']}
df = pd.DataFrame(data=d)
sample_lst = []
for q in df['col1']:
nltk_tokens = nltk.word_tokenize(q)
for w in nltk_tokens:
sample_lst.append(wordnet_lemmatizer.lemmatize(w, pos='v'))
print(sample_lst)
该代码有效并将 wordnet_lemmatizer.lemmatize 附加到列表中,但是,我想将结果保存在原始输入旁边的 CSV 文件中,如下所示
Col1 Col2
AI is our friend and it has been friendly IA be our friend and it have be friendly
AI and humans have always been friendly AI and humans have always be friendly
我试图做一个 ''.join() 但结果不是我所期望的,任何关于如何重新加入句子并将其添加到新列中的想法提前谢谢。
解决方案
利用:
#create list for all values
out = []
for q in df['col1']:
#create list for each value
sample_lst = []
nltk_tokens = nltk.word_tokenize(q)
for w in nltk_tokens:
sample_lst.append(wordnet_lemmatizer.lemmatize(w, pos='v'))
#join lists by space
out.append(' '.join(sample_lst))
df['Col2'] = out
print (df)
col1 \
0 AI is our friend and it has been friendly
1 AI and human have always been friendly
Col2
0 AI be our friend and it have be friendly
1 AI and human have always be friendly
嵌套列表理解的另一个解决方案:
df['Col2'] = [' '.join(wordnet_lemmatizer.lemmatize(w, pos='v')
for w in nltk.word_tokenize(q))
for q in df['col1']]
推荐阅读
- flutter - 如何定位出现在 Flutter 中所有其他元素之上的元素
- python - 如何使用 python 运行 cURL 请求
- sql - 不起作用时按顺序使用表格
- javascript - Oracle Apex 使用 SweetAlert js 代码停止动态操作
- sql - 有没有办法将数组引用到 PostgreSql 中的另一个表?我是通过出错来做到的
- blob - 如何从服务工作者的 localForage 返回 blob 项目?
- html - 有没有办法使用 HTML 和 Thymeleaf 过滤从 Spring Boot 端点返回的数据?
- azure - Azure Blob 存储:虚拟文件夹结构与 Blob 索引标签
- excel - 在 PowerQuery 中将列表转换为具有布尔值的列
- html - 相同的 CSS 动画不会在两个事件上运行 [仅限 HTML/CSS]