基于STR Python中的条件插入','

2024-05-23 17:52:32 发布

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

我正在处理一个很长的街道名称列表,如下所示:

1820 W 9000 SWest Jordan
455 S 500 ESalt Lake City
555 S 200 WBountiful
1000 N Green Valley PkwyHenderson
10100 W Tropicana AveLas Vegas
10305 S 1300 ESandy
10600 Southern Highlands PkwyLas Vegas
10616 S Eastern AveHenderson
111 Coors Blvd NWAlbuquerque
1170 E Gentile StLayton
1174 W 600 NSalt Lake City
1200 W Main StRiverton
....
....

我试图在城市名称前插入一个“,”,它总是出现在一个小写字符之后,后跟一个空格和一个大写字符。你知道吗

所以这就是我的想法:

我该怎么写一些东西,或多或少地说:

for cities in lst:
    if [char] is lower and [nextchar] is UPPER:
        [insert] ',' before UPPER

Tags: 名称city列表isgreen字符街道upper
3条回答
cities = [re.sub(r'(?<=[a-z])(?=[A-Z])', ',', x) for x in cities]

按照@Martijn的建议,在一组中取最后一个大写字母,也许:

import re
def fix(s):
    return re.sub("([a-z]|[A-Z]+)([A-Z])",r"\1,\2", s)

这给了

>>> for line in lines:
...     print fix(line)
...     
1820 W 9000 S,West Jordan
455 S 500 E,Salt Lake City
555 S 200 W,Bountiful
1000 N Green Valley Pkwy,Henderson
10100 W Tropicana Ave,Las Vegas
10305 S 1300 E,Sandy
10600 Southern Highlands Pkwy,Las Vegas
10616 S Eastern Ave,Henderson
111 Coors Blvd NW,Albuquerque
1170 E Gentile St,Layton
1174 W 600 N,Salt Lake City
1200 W Main St,Riverton

[免责声明:我对正则表达式很糟糕。]

像这样的?你知道吗

for big_index, cities in enumerate(lst):
    for index, char in enumerate(cities):
        if char == char.lower() and cities[index+1] != cities[index+1].lower():
            lst[big_index] = cities[:index] + "," + cities[index:]

免责声明**未经测试。因为我没有你所有的数据,我不会尝试,但这应该会给出你描述的输出

**编辑:事实上,看起来您的数据根本没有遵循这些规则。就像注释中的例子一样,Coors Blvd NWAlbuquerque怎么样?不管怎样,除非你改变你的问题,否则我会把密码留在这里

相关问题 更多 >