我是 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'}]
关于Python:如何从字符串中提取所需信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3533072/