【问题标题】:finding integer and string from split sentence从拆分句子中查找整数和字符串
【发布时间】:2016-11-13 18:17:37
【问题描述】:

我需要拆分这个字符串:

"We shall win 100 dollars in the next 2 years" 

并返回一个包含整数和字符串列表的元组([100,2],[We,shall,win,dollars,in,the,next,years])

到目前为止我的尝试:

lst_int =[]
    lst_str =[]
    tup_com =(lst_int,lst_str)
    words = input_string.split()
    for i in words:
        if i == int():
            lst_int.append(i)
        elif i != int():
            lst_str.append(i)
    return tup_com

【问题讨论】:

    标签: python string python-2.7 python-3.x


    【解决方案1】:

    你可以用简单的正则表达式来做到这一点

    import re
    s = "We shall win 100 dollars in the next 2 years"
    
    t = (re.findall("[0-9]+",s),re.findall("[a-zA-Z]+",s))
    

    【讨论】:

    • 另一种很棒的方法。谢谢!
    【解决方案2】:

    如果你稍微调整一下你的条件,这可以实现。 i == int() 并没有真正按照你的想法去做; int() 返回 0 所以你基本上是在不断检查 i == 0 是否永远是 False(导致所有内容都附加到 lst_str

    相反,在您的for 循环中使用str.isdigit,如下所示:

    if i.isdigit():
        lst_int.append(i)
    else:
        lst_str.append(i)
    

    str.isdigit 遍历您提供的字符串中的字符并评估它们是否都是数字(并且字符串非空)。

    然后,tup_com 结果:

    (['100', '2'], ['We', 'shall', 'win', 'dollars', 'in', 'the', 'next', 'years'])
    

    顺便说一句,这里不需要tup_com,只需返回以逗号分隔的列表并创建一个包含它们的元组。

    即:

    return lst_int, lst_str
    

    【讨论】:

      【解决方案3】:

      您可以使用多种方法来做到这一点:

      1) 检查isdigit:

      sentence = "We shall win 100 dollars in the next 2 years"
      
      str_list=[]
      int_list=[]
      for word in sentence.split():
         if word.isdigit():
            int_list.append(int(word))  # cast at the same time
         else:
            str_list.append(word)
      

      问题:如果数字为负数,您必须检查包含减号、空格字符的数字,这些数字仍被视为有效数字,这使得isdigit 变得更加复杂。这可能会导致您使用正则表达式,它更复杂,并在使用正则表达式进行整数解析时打开潘多拉魔盒......(我什至没有提到浮点数)

      2)依赖python整数解析:

      str_list=[]
      int_list=[]
      for word in sentence.split():
          try:
              int_list.append(int(word))
          except ValueError:
              str_list.append(word)
      

      由于异常处理有点慢,但在所有情况下都可以正常工作,甚至可以推广到浮点数。

      【讨论】:

      • 非常感谢您的出色解释。谢谢漂亮的先生!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多