Python 有没有一种简单的方法可以将数据帧上的大字符串拆分为相等数量的单词?
我有一个由1000行组成的数据集,其中包含给定的作者和属于该作者的大量文本。我最终试图实现的是将文本行分解为多行,其中包含相同数量的单词,如:Python 有没有一种简单的方法可以将数据帧上的大字符串拆分为相等数量的单词?,python,pandas,string,split,word,Python,Pandas,String,Split,Word,我有一个由1000行组成的数据集,其中包含给定的作者和属于该作者的大量文本。我最终试图实现的是将文本行分解为多行,其中包含相同数量的单词,如: Author - - - - - - - - text Jack - - - - - - -- - -"This is a sentence that contains eight words" John - - - - - - - - -"This is also a sentence containing eigh
Author - - - - - - - - text
Jack - - - - - - -- - -"This is a sentence that contains eight words"
John - - - - - - - - -"This is also a sentence containing eight words"
因此,如果我想对4个单词块进行测试,应该是:
Author- - - - - - text
Jack- - - - - - - "This is a sentence"
Jack- - - - - - -"that contains eight words"
John- - - - - - - "This is also a"
John- - - - - - - "sentence containing eight words"
我已经可以使用textwrapper按字符数来做了,但理想情况下我希望按单词数来做。
我们将非常感谢任何可能导致这一点的帮助,
谢谢 假设您使用的pandas>=0.25(支持),您可以使用以下方法:
def split_by_equal_number_of_words(df, num_of_words, separator=" "):
"""
1. Split each text entry to a list separated by 'separator'
2. Explode to a row per word
3. group by number of the desired words, and aggregate by joining with the 'separator' provided
:param df:
:param num_of_words:
:param separator:
:return:
"""
df["text"] = df["text"].str.split(separator)
df = df.explode("text").reset_index(drop=True)
df = df.groupby([df.index // num_of_words, 'author'])['text'].agg(separator.join)
return df
使用空格作为单词
字符串之间的分隔符。拆分(“”
)。然后使用切片splitted_list[:]