【问题标题】:Find the words in a list, then remove the word and any other trailing words in the column在列表中查找单词,然后删除该单词和列中的任何其他尾随单词
【发布时间】:2018-07-13 07:47:23
【问题描述】:

如何在列表中找到单词并删除找到的单词之后的任何其他单词?

例如:

remove_words = ['stack', 'over', 'flow']

输入:

0    abc test test stack yxz
1    cde test12 over ste
2    def123 flow test123
3    yup over 4562

想从 pandas 数据框列中的 remove_words 列表中找到单词,然后删除这些单词和之后的任何单词。

结果:

0    abc test test
1    cde test12 
2    def123
3    yup

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    split 用于| 的所有连接值用于正则表达式OR 并首先选择lists by str[0]

    remove_words = ['stack', 'over', 'flow']
    
    #for more general solution with word boundary
    pat = r'\b{}\b'.format('|'.join(remove_words))
    df['col'] = df['col'].str.split(pat, n=1).str[0]
    print (df)
                  col
    0  abc test test 
    1     cde test12 
    2         def123 
    3            yup 
    

    【讨论】:

      【解决方案2】:

      第一步是检查输入是否有值,如果没有,你可以直接返回整个输入

      if "stack" or "over" or "flow" not in input: 
          return input
      

      现在是移除部分。我认为最好的方法是遍历输入数组中的每个值(我假设它是一个数组)并调用str_replace

      【讨论】:

        【解决方案3】:

        我没有用 pandas 数据框编写,但是任何语言的音乐会都应该是相同的,只需遍历所有单词并使用带有空字符串的替换方法。

        【讨论】:

          【解决方案4】:
          remove_words = ['stack', 'over', 'flow']
          inputline = "abc test test stack yxz"
          for word in inputline.split(" "):
              if word in remove_words:
                 print(inputline[:test.index(word)])
          

          这会将输入的字符串拆分为一个列表,然后在 remove_words 列表中找到任何单词的索引,并将列表的其余部分切掉。只需要做一个循环来替换整个数据集的核心字符串。

          【讨论】:

            猜你喜欢
            • 2011-06-13
            • 1970-01-01
            • 2015-11-19
            • 1970-01-01
            • 1970-01-01
            • 2012-10-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-28
            相关资源
            最近更新 更多