python-3.x - 恢复原始换行符 pandas \n
问题描述
背景
我有以下示例 df
import pandas as pd
df = pd.DataFrame({'Text' : ['\n[STUFF]\nBut the here is \n\nBase ID : 00000 Date is Here \nfollow\n',
'\n[OTHER]\n\n\nFound Tom Dub \nhere\n BATH # : E12-34567 MR # 000',
'\n[ANY]\nJane Ja So so \nBase ID : 11111 Date\n\n\n hey the \n\n \n \n\n\n'],
'Alt_Text' : ['[STUFF]But the here is Base ID : *A* Date is Here follow',
'[OTHER]Found *B* *B* here BATH # : *A* MR # *C*',
'[ANY]*B* *B*So so Base ID : *A* Date hey the '],
'ID': [1,2,3]
})
目标
1) 创建一个新列2) 重新获得列中存在New_Text
的原始换行符,但包含列中的内容\n
Text
Alt_Text
例子
Text
列,行0
:
\n[STUFF]\nBut the here is \n\nBase ID : 00000 Date is Here \nfollow\n
Alt_Text
列,行0
:
[STUFF]But the here is Base ID : *A* Date is Here follow
想
\n[STUFF]\nBut the here is \n\nBase ID : *A* Date is Here \nfollow\n
期望的输出
Text Alt_Text ID New_Text
0 \n[STUFF]\nBut the here is \n\nBase ID : *A* Date is Here \nfollow\n
1 \n[OTHER]\n\n\nFound *B* *B* \nhere\n BATH # : *A* MR # *C*
2 \n[ANY]\nJ*B* *B* So so \nBase ID : *A* Date\n\n\n hey the \n\n \n \n\n\n
试过了
我环顾四周,包括Python 中的 Wrap multiline string (preserving existing linebreaks)?并 使用 Pandas 读取 Excel 数据并保留单元格值的换行符,但似乎没有一个是我想要做的。
问题
如何实现我想要的输出?
解决方案
我们正则表达式拆分 Text
并Alt_Text
在模式中使用捕获括号:
如果在模式中使用捕获括号,则模式中所有组的文本也会作为结果列表的一部分返回。
然后我们zip
都列出了包含换行符的分隔符Text
和其他任何内容,Alt_Text
并将join
结果列表放入New_Text
:
def insert_line_breaks(text, alt_text):
regex = re.compile(r'([^ \n\[\]]+)')
text = regex.split(text)
alt_text = regex.split(alt_text)
return ''.join([t if '\n' in t else a for t,a in zip(text,alt_text)])
df['New_Text'] = df.apply(lambda r: insert_line_breaks(r.Text, r.Alt_Text), axis=1)
我想在所需输出的第二行*B*
和So
最后一行之间应该有一个空格,Alt_Text
而在J
第一行之前应该是一个错字。*B*
在这种情况下,我们得到:
>>> df.New_Text
0 \n[STUFF]\nBut the here is \n\nCase ID : *A* Date is Here \nfollow\n
1 \n[OTHER]\n\n\nFound *B* *B* \nhere\n BATH # : *A* MR # *C*
2 \n[ANY]\n*B* *B* So so \nCase ID : *A* Date\n\n\n hey the \n\n \n \n\n\n
推荐阅读
- android - 如果 Android VersionCode 达到 2100000000,接下来会发生什么?
- excel - 过滤器留空时显示所有列数据
- stripe-payments - 更新条带价格后会发生什么?
- sql - DECLARE @table TABLE ...没有工作变量
- flutter - 在没有回调监听器的情况下更改滚动视图偏移量
- php - 我在 blueimp(文件上传插件)中遇到错误,它工作正常,xampp 服务器但不在在线服务器上
- kql - 时间戳列顺序的 Kusto 查询问题
- android - Kotlin 中的“ClassName::class”与“ClassName::class.java”?
- c# - 如何在 linq 中进行内部选择?
- excel - 单元格格式excel