【问题标题】:Show the word found from a set of words within a column显示从列中的一组单词中找到的单词
【发布时间】:2022-07-07 15:22:42
【问题描述】:

我正在尝试通过 python 在数据框行内的列表中搜索单词,以获得两个新列,显示以逗号分隔的单词,另一列显示找到的单词数

这是我的字符串列表

string_list = ["never sounded", "she", "was time", "against"]

and this is the df I want obtain

【问题讨论】:

  • 看看str.extract
  • 请提供一个可重现的输入/输出示例(如文本
  • 你能详细说明这个问题吗?

标签: python pandas text


【解决方案1】:

首先我用字符串逐字分隔,所以你只能找到完全匹配的单词,所以如果你搜索单词“a”之类的东西,它不会只找到字符串中的每个字母“a”

wordsToFind = "beautiful sunny"
stringToSearch = "today will be a beautiful sunny day"

foundStrings = []
stringsToFind = wordsToFind.split()

for s in stringsToFind:
    list_stringSeparatedByWord = stringToSearch.lower().split()
    if list_stringSeparatedByWord.count(s.lower()) > 0:
        foundStrings.append(s)

print (foundStrings)

【讨论】:

    【解决方案2】:

    从斯蒂芬的回答延伸。这是一个声明性的 Python 方法。

    听起来您正试图找到您正在寻找的单词和文本中存在的单词的交集。您可以使用设置交集来实现此目的。 https://docs.python.org/3.8/library/stdtypes.html#frozenset.intersection

    代码:

    text = "today will be a beautiful sunny day"
    get_words = "beautiful sunny"
        
    found_words = list(set(text.split(' ')).intersection(set(get_words.split(' '))))
    

    结果:

    found_words == ['beautiful', 'sunny']
    

    为了在 pandas 中跨多行使用它,您可以使用 df.assign。这将根据当前列的操作创建一个新列。 https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html

    代码:

    get_words = "beautiful sunny"
    word_finder_formatter = lambda row: ', '.join(list(set(row['text'].split(' ')).intersection(set(get_words.split(' ')))))
    word_counter = lambda row: len(list(set(row['text'].split(' ')).intersection(set(get_words.split(' '))))
    
    df = df.assign(found_words=word_finder_formatter, found_words_count=word_counter)
    

    结果:

    text                                  | found_words           | found_words_count
    ----------------------------------------------------------------------------------
    today will be a beautiful sunny day   | beautiful, sunny day  | 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多