python - 识别给定单词序列前面的字符串

标签 python regex

我有一个文本句子“我父亲是美国人,他很帅”和“我母亲来自北美,她很好”。

我需要提取单词 American(在本例中为 an)和 America(在本例中为North) 显示到控制台。

注意:单词 America 在第二句中有一个后缀 America + n 使其成为 American

到目前为止我的代码:::

for line in words:
    for word in line.strip().split(' '):
         // HERE I SHOULD WRITE THE CODE TO IDENTIFY THE WORD BEFORE THE STRING 'AMERICA*'

最佳答案

这个怎么样?

import re

s = """
My Father is an American, and he is handsome
My Mother is from North America and she is nice
"""

print re.findall(r"(\w+)\sAmerica", s)

打印:

['an', 'North']

关于python - 识别给定单词序列前面的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18164916/

相关文章:

python - 如何在 python 中从头开始设置(新的)monetdb 数据库?

python - AssertionError : Could not compute output Tensor

python - 增加给定序列的字符

Javascript RegExp 将字符串中的所有数字减一

java - 从java中的字符串中获取<img>值

javascript - 在输入字段中每第 5 个数字后动态添加一个空格的纯 Javascript 方法

python - 两个 imshow 图相互叠加,使用 slider 更改图层的不透明度

javascript - 在预提交javascript中清除 "bad"字符的表单提交数据?

Regex Ruby 如何对括号内的每个单词进行分组

python - 导入错误 : cannot import name 'keras'