regex - 如何使用正则表达式提取所有使用Python的特定模式之间的单词
问题描述
df['text'][0] = 'beautiful place\nlocation: United States Of America\ntraveldate:'
我需要在“位置”之后和\n
字符之前提取所有单词。
我在下面的代码中尝试了正则表达式模式:
def Location(txt):
txt1 = re.findall(r"(location:\s[A-Z]\w+)", txt)
return txt1
df['Location'] = df['text'].apply(lambda x : Location(x))
实际输出:['location: United']
预期输出:'United States Of America'
解决方案
str.replace
与捕获组一起使用:
df['Location'] = df['text'].str
.replace(r'^.*\blocation:\s*([^\n]+).*$', r'\1', flags=re.DOTALL)
推荐阅读
- excel - 在 Excel 中将变量添加到索引匹配函数
- javascript - React Axios - JSON Get 响应未从 render() 显示 - Riot API
- apache-kafka - Kafka Streams 加入不相关的流
- python - bbox、label、conf = cv.detect_common_objects(img) 命令无法正常工作
- javascript - 如何在javascript中实现双端队列数据结构?
- mysql - 如何减去两个 sql 时间戳字段,然后以小时为单位返回时差
- c# - SignalR .NET 框架与 SignalR .NET Core 功能
- python - 从另一个形状不同的数据帧中替换数据帧
- java - 如何修复 STS4 中“导入为 gradle 项目”、“从系统打开文件”的错误?
- java - Jsp div 顺序在渲染时被更改