Python正则表达式,用于从字符串中标识城市名称

2024-10-04 05:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python3.4中的正则表达式,如何从下面的文本中提取城市名称?在

replacement windows in seattle wa
basement remodeling houston texas
siding contractor new york ny
windows in elk grove village

有时城市名称前面有\sin\s,有时没有。有时它有一个通用词,如“windows”、“removing”。。。什么都可以。有时在结尾处没有州全名或州缩写。在

上面有一个正则表达式可以捕捉到这些条件吗?在

这是我迄今为止尝试过的,但它只捕捉到了“西雅图”。在

^{pr2}$

Tags: in文本名称newwindowsyorkwareplacement
2条回答
import re

l = ['replacement windows in seattle wa',
     'basement remodeling houston texas',
     'siding contractor newyork ny',
     'windows in elk grove village']

p = re.compile(r"(\w+)\s(?:(wa | texas | ny | village))", re.VERBOSE)

for words in l:
    print p.search(words).expand(r"\g<1> <  the code is  > \g<2>")

正则表达式是不可能实现的。正则表达式需要字符串模式才能工作。在您的例子中,似乎模式要么不存在,要么可以采取多种形式。在

你能做的就是使用一个搜索效率高的数据结构,把你的字符串拆分成单词。然后检查每个单词,看它是否在搜索效率高的数据结构中。在

相关问题 更多 >