熊猫:除非在点之前有数字或字符,否则在点上拆分
Posted
技术标签:
【中文标题】熊猫:除非在点之前有数字或字符,否则在点上拆分【英文标题】:pandas: split on dot unless there is a number or a character before dot 【发布时间】:2022-01-12 18:10:12 【问题描述】:我有一个如下的数据框:
import pandas as pd
df = pd.DataFrame('text':['she is a. good 15. year old girl. she goes to school on time.', 'she is not an A. level student. This needs to be discussed.'])
要在 (.) 上拆分和爆炸,我做了以下操作:
df = df.assign(text=df['text'].str.split('.')).explode('text')
但是我不想在每个点之后都分开。所以我想在点上拆分,除非点被数字包围(例如 22.、3.4)或围绕点的单个字符(例如 a.、a.b.、b.d
desired_output:
text
'she is a. good 15. year old girl'
'she goes to school on time'
'she is not an A. level student'
'This needs to be discussed.'
所以,我也尝试了以下模式,希望忽略单个字符和数字,但它从句子的最后一个单词中删除了最后一个字母。
df.assign(text=df['text'].str.split(r'(?:(?<!\.|\s)[a-z]\.|(?<!\.|\s)[A-Z]\.)+')).explode('text')
我编辑了模式,所以现在它匹配数字或单个字母之后的所有类型的点:r'(?:(?
【问题讨论】:
抱歉,如果没有要拆分的特定标记,您如何在句尾拆分?也许你可以像你说的那样拆分,前提是在点之前没有数字或字符,但这是这个句子的临时解决方案,如果在其他句子中你有这个规则无效怎么办? 你将如何确定一个句子的结尾?在我看来,这不是很直接。 我想在点上分割,除非点被数字包围(例如 22.、3.4)或围绕点的单个字符(例如 a.、ab、bd) @zarakolagar 是你想要的输出的第一句不正确,因为你的逻辑在这里? 如果您的意思是使用最后一个模式 (r'(?:(? gir) 【参考方案1】:#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
input = 'she is a. good 15. year old girl. she goes to school on time. she is not an A. level student. This needs to be discussed.'
sentences = re.split(r'\.', input)
output = []
text = ''
for v in sentences:
text = text + v
if(re.search(r'(^|\s)([a-z]1|[0-9]+)$', v, re.IGNORECASE)):
text = text + "."
else:
text = text.strip()
if text != '':
output.append(text)
text = ''
print(output)
输出:
['she is a. good 15. year old girl', 'she goes to school on time', 'she is not an A. level student', 'This needs to be discussed']
【讨论】:
已编辑以匹配以空格开头和之前的空格:(^|\s)
以上是关于熊猫:除非在点之前有数字或字符,否则在点上拆分的主要内容,如果未能解决你的问题,请参考以下文章