Skip to main content
 首页 » 编程设计

Python:如何从字符串中提取所需信息

2025年05月04日17exmyth

我是 Python 新手。 Python 中有 StringTokenizer 吗?我可以逐字符扫描和复制吗?

我有以下输入字符串

data = '123:Palo Alto, CA -> 456:Seattle, WA 789' 

我需要从该字符串中提取两个(城市、州)字段。这是我写的代码

name_list = [] 
while i < len(data)): 
      if line[i] == ':': 
          name = '' 
          j = 0 
          i = i + 1 
          while line[i] != '-' and line[i].isnumeric() == False: 
             name[j] = line[i]   # This line gives error 
             i = i + 1 
             j = j + 1 
          name_list.append(name) 
      i = i + 1 

我该怎么办?

请您参考如下方法:

data = '123:Palo Alto, CA -> 456:Seattle, WA 789' 
citys = [] 
for record in data.split("->"): 
    citys.append( 
        re.search(r":(?P<city>[\w\s]+),\s*(?P<state>[\w]+)",record) 
        .groupdict() 
    ) 
 
print citys 

给予:

[{'city': 'Palo Alto', 'state': 'CA'}, {'city': 'Seattle', 'state': 'WA'}]