[英]Replace words in a text using python
我在 dataframe 中有一个带有自由文本的列。 我想替换文本中以 AA 开头并以 AA 结尾的单词。 谁能建议如何做到这一点?
这是使用替换 str 方法和正则表达式模式的简单解决方案
>>> df=pandas.DataFrame({'example':['AAhelloAA','Arreviour','Dunno this is a example of it','a knee','an arrow','AAnother example ofAA']})
>>> print(df)
example
0 AAhelloAA
1 Arreviour
2 Dunno this is a example of it
3 a knee
4 an arrow
5 AAnother example ofAA
>>> df['example'].str.replace(r'(AA).*?(AA)','NEW CHANGE!')
0 NEW CHANGE!
1 Arreviour
2 Dunno this is a example of it
3 a knee
4 an arrow
5 NEW CHANGE!
Name: example, dtype: object
必须澄清正则表达式中的模式适用于任何以 AA 开头和结尾的文本。
使用正则表达式捕获组并随心所欲地处理它。 要仅返回每侧由 AA 包围的文本,请执行以下操作:
df.column.replace(r"AA(.*)AA", r"\1", regex=True)
\1
是代表被 AA 包围的文本部分的正则表达式组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.