【问题标题】:Extracting information from Strings in Python在 Python 中从字符串中提取信息
【发布时间】:2020-05-11 08:43:26
【问题描述】:

格式为 "FirstName LastName Type_Date-Time_ref_PhoneNumber"

所有这些都是一个字符串

示例:“Yasir Pirkani MCD_20201105-134700_abc123_12345678”

我想从这个字符串中提取姓名、类型、日期、时间、参考、电话号码。

【问题讨论】:

  • 请添加一些代码以显示您解决问题的努力
  • 你可以试试re.split(re.split('[\s_]+', my_string)
  • 到目前为止,我已经能够通过搜索“”来搜索日期、时间、参考和电话号码 text = 'Yasir Pirkani MCD_20201105-134700_abc123_12345678' x = [i for i in range(len(file)) if file.startswith('', i)] date= text[x[0]+1:x[0]+5] time = file[x[0]+10 :x[0]+16]

标签: python string parsing text


【解决方案1】:

有多种方法可以做到这一点,其中一种是使用正则表达式。

s = "Yasir Pirkani MCD_20201105-134700_abc123_12345678"
splited_s = re.split('[\s_]+', s)
# splited_s -> ['Yasir', 'Pirkani', 'MCD', '20201105-134700', 'abc123', '12345678']

然后你就可以访问splited_s的每个元素并进行适当的调整

【讨论】:

    【解决方案2】:

    你可以的

    a = "Yasir Pirkani MCD_20201105-134700_abc123_12345678"
    name = " ".join(a.split(" ")[:2])
    Type, Date, ref, Phonenumber = a.replace(name, "").strip().split("_")
    Time = Date[Date.find("-")+ 1:]
    Date = Date.replace(f"-{Time}", "")
    print(name, Type, Date, Time, ref, Phonenumber)
    

    那会输出

    ('Yasir Pirkani', 'MCD', '20201105', '134700', 'abc123', '12345678')
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多