繁体   English   中英

在Python中将长字符串分割成地址列表

[英]Split long string of addresses into list of addresses in Python

我在python中有一两千个地址的字符串,像这样:

'123 Chestnut Way 4567 Oak Lane 890 South Pine Court'

将这个长字符串拆分为单独地址的最简单方法是什么? 我试图编写一个程序,该程序基于3个或4个字符在47 < ord(i) < 58的行中进行拆分,但是遇到了麻烦。

假设所有地址都与给定的地址相同,则可以使用re.findall

>>> from re import findall
>>> string = '123 Chestnut Way 4567 Oak Lane 890 South Pine Court'
>>> findall("\d+\D+(?=\s\d|$)", string)
['123 Chestnut Way', '4567 Oak Lane', '890 South Pine Court']
>>>

上面解释上面使用的所有Regex语法,但以下是快速分解:

\d+   # One or more digits
\D+   # One or more non-digits
(?=   # The start of a lookahead assertion
\s    # A space
\d|$  # A digit or the end of the string
)     # The end of the lookahead assertion

您可以使用正则表达式轻松完成此操作,

import re
txt = '123 Chestnut Way 4567 Oak Lane 890 South Pine Court'
re.findall( r'\d+', txt )

最后将返回所有数字的运行,

['123', '4567', '890']

然后,您可以使用该信息来解析字符串。 有很多方法,但是您可以在原始字符串中找到数字的索引,然后在中间找到文本。 您还可以使regeular表达式更高级。 以下内容将匹配任意数量的数字,后跟一个空格,后跟任意数量的非数字(包括空格)

re.findall( r'\d+ \D+', txt )

并会回来,

['123 Chestnut Way ', '4567 Oak Lane ', '890 South Pine Court']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM