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

标签 python

我是 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/

相关文章:

Python 多处理如何优雅地退出?

python - abort(400) 引发 500 内部服务器错误 - Flask 1.0

python - 如何为异步创建自定义传输?

python - 如何迭代不相等的嵌套列表以创建新列表 Python

python - 带有 Django 和 MongoEngine 的 Python 中的 Unicode

python - Django 和 Python + uWSGI

python - 获取 fixture 中的主键(id)(Python,SQLAlchemy)

python - 比较Python 3中字典中的列表类型值

python - 将带括号的字符串转换为嵌套列表

python - 我在使用 PyVirtualDisplay==0.2.5 包运行使用虚拟显示器( headless (headless)模式)的测试时遇到问题