【问题标题】:Extract specific string in a list of string in Python [duplicate]在Python中的字符串列表中提取特定字符串[重复]
【发布时间】:2021-07-19 11:53:09
【问题描述】:

我有一个字符串列表:

List = ["A: I want to do something cool!|B: Really? What is that?|A: Lets me show you.", "A: How do you think about it?!|B: It's not bad|A: Thank you. What do you up to?|B: I have no idea. Lets hangaround|B: or maybe we can go for a drink."]

我想将信息提取到 2 个单独的列表中,每个列表都包含 A 和 B 的内容。

例如:

List_A = ['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']

List_B = ['B: Really? What is that?', 'B: It's not bad', 'I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']

有没有办法在 Python 中执行任务?非常感谢您的帮助!

【问题讨论】:

    标签: python string nlp


    【解决方案1】:

    尝试使用列表推导:

    List = sum([i.split('|') for i in List], [])
    List_A = [i for i in List if i[0] == "A"]
    List_B = [i for i in List if i[0] == "B"]
    

    现在:

    print(List_A)
    

    应该是:

    ['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']
    

    还有:

    print(List_B)
    

    应该是:

    ['B: Really? What is that?', "B: It's not bad", 'B: I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']
    

    【讨论】:

      【解决方案2】:

      您可以拆分| 上的每个字符串,遍历每个句子并根据每个句子的第一个字母将它们添加到字典中。

      from collections import defaultdict
      
      d = defaultdict(list)
      for line in data:
          split = line.split("|")
          for sentence in split:
              key = sentence[0]
              d[key].append(sentence)
      
      print(d["A"])
      >> ['A: I want to do something cool!',
       'A: Lets me show you.',
       'A: How do you think about it?!',
       'A: Thank you. What do you up to?']
      
      print(d["B"])
      >> ['B: Really? What is that?',
       "B: It's not bad",
       'B: I have no idea. Lets hangaround',
       'B: or maybe we can go for a drink.']
      

      【讨论】:

        【解决方案3】:

        一个简单的解决方案 -

        list1 = []
        list2 = []
        for j in List:
            for i in j.split('|'):
                if i.startswith('A'):
                    list1.append(i)
        
                if i.startswith('B'):
                    list2.append(i)
        
        
        print(list1)
        print()
        print(list2)
        

        结果:

        ['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']
        
        ['B: Really? What is that?', "B: It's not bad", 'B: I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']
        

        您可以改用列表推导。但它被其他用户回答了

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-21
          • 2021-05-08
          • 2020-11-04
          • 2017-12-04
          • 2014-07-26
          相关资源
          最近更新 更多