给一个文本文件,我希望对POS标签列下的每个句子将单词进行分组,并以;分隔。
我尝试了“ alvas”的类似解决方案。但是该解决方案给出了pos标签列下的单词数。我希望将实际单词分组。
from collections import Counter
from itertools import chain
import pandas as pd
from nltk import word_tokenize, pos_tag
df = pd.read_csv('test.csv', delimiter=',')
df.columns = ['sent']
tok_and_tag = lambda x: pos_tag(word_tokenize(x))
df['lower_sent'] = df['sent'].apply(str.lower)
df['tagged_sent'] = df['lower_sent'].apply(tok_and_tag)
possible_tags = sorted(set(list(zip(*chain(*df['tagged_sent'])))[1]))
def add_pos_with_zero_counts(counter, keys_to_add):
for k in keys_to_add:
counter[k] = counter.get(k, 0)
return counter
# All in one.
df['sent_vector'] = df['tagged_sent'].apply(lambda x:
[count for tag, count in sorted(
add_pos_with_zero_counts(
Counter(list(zip(*x))[1]),
possible_tags).most_common()
)
]
)
df2 = pd.DataFrame(df['sent_vector'].tolist())
df2.columns = possible_tags
print(df2)
(用户“ alvas”采用的代码)
文字 约翰去酒店吃素食早餐, 然后他去了宏cer购物中心买一台笔记本电脑, 他查看了许多模型并选择了Windows 10模型, 他花了2500美元将它带回家
对于上面的代码,上面的代码给出如下输出:
$ , CC CD DT IN JJ NN NNS PRP RB TO VB VBD VBG
0 0 1 1 0 0 0 0 5 0 0 0 1 0 1 0
1 0 1 0 0 1 0 0 2 0 1 1 2 2 1 1
2 0 1 1 1 1 1 1 1 2 1 0 0 1 1 0
3 1 0 1 1 0 1 0 1 0 3 0 0 0 2 0
但是我需要类似示例的输出:
$ , CC CD DT IN JJ NN NNS PRP RB TO VB VBD VBG
0 , John;hotel to went
1 acer;laptop buy
所有单词都需要在其各自的pos标签列下分组。 任何帮助表示赞赏。谢谢。