如何在数据帧中只保留字符串的某些句子

2024-09-30 16:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的熊猫数据框架中,我在article列下有100篇新闻文章。每一篇新闻文章都是一个字符串。我只想保留每个字符串的前3个句子,但我不知道如何保留。(我注意到每个句子都用\n隔开)

请提出可能的解决办法

数据帧如下所示:

print("Reading data from csv file")

print(read)
Reading data from csv file
    Unnamed: 0                                            article
0            0  \nChina’s ambassador to the US wants American ...
1            1  \nMissouri has become the first state to file ...
2            2  \nThe US is slamming the Communist Chinese gov...
3            3  \nSecretary of State Mike Pompeo on Thursday r...
4            4  \nThe US — along with Russia, China and India ...
..         ...                                                ...
95          95  \nChina has reported no new deaths from the co...
96          96  \nThe World Health Organization on Tuesday fin...
97          97  \nAfter two months of being shut down due to t...
98          98  \nSome coronavirus patients may suffer neurolo...
99          99  \nChina may be past the worst of the COVID-19 ...

[100 rows x 2 columns]

Tags: oftheto数据字符串fromarticle文章
1条回答
网友
1楼 · 发布于 2024-09-30 16:38:36

假设字符串的格式为:

"\nA\nB\nC\nD\nE\nF\n"

您可以使用以下方法将它们减少到前三行:

x = "\nA\nB\nC\nD\nE\nF\n"
x = "\n".join(x.split("\n", maxsplit=4)[1:4])

这将获取字符串,拆分为行列表,并将前三行与\n连接在一起。因此,在上述示例中,x变为:

'A\nB\nC'

在Pandas中,您可以将其应用于具有以下内容的列:

df['article'].apply(lambda x: "\n".join(x.split("\n", maxsplit=4)[1:4]))

一个小注意事项是,如果少于三行,它将在这些字符串的末尾留下一个零散的\n,因此您可以在lambda表达式的末尾用一个条带将其去掉,或者确保每一篇文章都以\n
{}结尾

正如你所问,在x = "\n".join(x.split("\n", maxsplit=4)[1:4])中发生的事情的机制如下:

对于每个字符串,请说x = "\nA\nB\nC\nD\nE\nF\n"

它被分成一个列表,使用"\n"作为分界点。所以:
x.split("\n", maxsplit=4)生成一个包含以下内容的列表:
['', 'A', 'B', 'C', 'D\nE\nF\n']。初始空条目是因为字符串以\n开头。我使用了maxsplit=4,因为我们将丢弃第三行之后的所有内容,所以没有必要拆分它们

现在我们想把'A', 'B', 'C'连接回一个字符串,它们在列表中的索引1,2,3处,所以我们使用[1:4]的切片(因为最后一个条目不包括在切片中),所以:
x.split("\n", maxsplit=4)[1:4]只包含:
['A', 'B', 'C']

最后,它们可以通过
"\n".join(x.split("\n", maxsplit=4)[1:4])重新连接在一起,这给了我们:
'A\nB\nC'这是前三行,用\n分隔

相关问题 更多 >