在潘达斯列中,句号后的第一个词都要大写。

1 人关注

我试图将存储在Pandas DF中的一些正文中的新句子的第一个字母(而且只有第一个)大写。

例如:我的数据框架有一个描述列,其中可能包含这样的文本。

这个产品有几个不同的特点。 it 也是 VERY cost effective. it 是我最喜欢的产品之一。

我希望我的结果是这样的。

这个产品有几个不同的特点。 It 也是 very cost effective. It 是我最喜欢的产品之一。

.capitalize()对我不起作用,因为它使同一正文中的新句子带有小写字母(即点和空格后的任何东西".".

有什么想法,我可以在不手动迭代行的情况下实现这一点?

谢谢你的时间。

2 个评论
Bill
这个问题的答案是否能解决你的问题。 将文本中句子的第一个词大写。 ?
python
pandas
string
periclesrocha
periclesrocha
发布于 2022-07-29
3 个回答
Farid Fakhry
Farid Fakhry
发布于 2022-07-29
0 人赞同

re.findIter将返回一个词组的所有匹配项(在我们的例子中是.)。

而你只需在它之前使用到降低。

例子(可能不适用,因为我手头没有IDE)。

mystring = "SOOOme wEirdly capiTalised STRINg. Followed By CHARACTERS"
mystring = myString.lower()
matches = re.finditer('[.]')
for match in matches:
  mystring[match.pos] = mystring[match.pos].upper()
    
Wojciech K
Wojciech K
发布于 2022-07-29
0 人赞同

假设你所有的句子都以点和空格字符结束/开始。替换代码0】你可以使用 split join capitalize 一起。

import pandas as pd
data = {'index' :[1, 2], "description": ["This product has several different features. it is also VERY cost effective. it is one of my favorite products.", "test sentence. another SENTENCE"]}
df = pd.DataFrame(data)
df["description"].apply(lambda x: ". ".join([sentence.capitalize() for sentence in x.lower().split(". ")]))

如果你想涵盖更复杂的情况,那么你可以使用nltkspacy标记器来分割句子。

mozway
mozway
发布于 2022-07-29
0 人赞同

使用regex来获取句子,并使用 capitalize 对其进行映射 str.replace

df['capitalize'] = df["description"].str.replace(r'[a-zA-Z][^.]+', lambda m: m.group().capitalize(), regex=True)

输出示例。

              description              capitalize
0  Abc def. gHi JKL. mno.  Abc def. Ghi jkl. Mno.

Used input:

import pandas as pd
data = {"description": ["Abc def. gHi JKL. mno."]}
df = pd.DataFrame(data)