如何解决在Pandas DataFrame中不仅要使单词彼此相邻
我有一个庞大但简单的Pandas DataFrame。 行看起来像这样:
index Text
1 This is a sample text
2 I am a test text
3 this is a test
我想为每一行创建字母组合。我做了什么:
from nltk.collocations import *
def create_bigram(word_list):
finder = BigramCollocationFinder.from_words(word_list)
return finder.ngram_fd.items()
test_str = "This is a sample text".split()
create_bigram(test_str)
哪个返回:
[(('This','is'),1),(('is','a'),(('a','sample'),(('sample','text'),1)]
但是我想记录每一行中每个单词的所有外观,而不仅仅是彼此相邻的单词。
赞:
index Bigrams
1 (this,is),(this,a),sample),text),(is,text)...
以此类推...
我希望它能够看到单词在一个DataFrame行中出现的频率。
nltk(或其他nlp库)是否有某种默认函数可以执行此操作,或者我必须自己执行此操作?
除了二元组或三元组或其他ngrams之外,我什么也找不到,但是它们都只对直接邻居进行计算,对吗?
对于30万行比“这是示例文本”更长的文本,进行简单的嵌套for循环来计算每种外观都是很费时间的。
编辑: 我想以某种方式想念明显的东西,但我看不到它。
解决方法
尝试一下:
from itertools import permutations
import pandas as pd
def create_bigram(word_list):
split_test_str = word_list.split()
perms = [','.join(element) for element in permutations(split_test_str,2)]
df = pd.DataFrame(data=[perms])
print(df)
test_str = 'This is a sample text'
create_bigram(test_str)
最简单的方法是创建字符串排列以获得所需的结果。
这可以通过itertools的功能置换来实现。 您可以在https://docs.python.org/3/library/itertools.html
上了解有关该功能的更多信息版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。