【问题标题】:looping through a list of string items and returning those that contain a substring in python循环遍历字符串项列表并返回那些在 python 中包含子字符串的项
【发布时间】:2018-12-23 06:11:36
【问题描述】:

我正在尝试遍历句子列表,并且只提取列表中包含子字符串(关键字)的项目,当在我的函数中使用 return 而不是 yield 时,我得到一个字符列表 vs yield 我得到完整的句子,但我知道它是一个生成器,并且想要包含该单词的每个句子的完整列表。是 .find() 导致问题还是有更好的方法从字符串项列表中提取?

import nltk
from nltk import *
import pandas as pd
f= open("filename.txt").read()
sent_list = sent_tokenize(f)

hunt = "youth" #keyword i'm searching for
def hunter(sent):
    for term in sent:
        if term.find(hunt) is not -1:
            yield term

complete_lst = [term for term in hunter(sent_list)]
df = pd.DataFrame({'key_term_sentences':complete_lst})

【问题讨论】:

  • 如果你只使用return而不是yield,那么你将得到第一个并且只有第一个。一个典型的模式是让hunter成为一个生成器,然后得到一个列表做list(hunter(sent_list))。
  • 另外,如果您不需要索引,请使用 if hunt in term
  • @BaileyParker 似乎可以解决问题,我的目标是确保生成器中生成包含子字符串的每个句子

标签: python string list nltk


【解决方案1】:

您的代码中有几个错误,其中一个是不使用split。修复后,一切正常。下面是一个工作示例:

In [31]: sent_list = ['this is first sentence for demo purposes', 
                      'this is second sentence containing youth and youthful', 
                      'this is 3rd sentence which is dummy one btw']

In [32]: hunt = 'youth'

# note that we need two `for` loops since the function takes list of sentences
In [33]: def hunter(sent_list):
    ...:     for sent in sent_list:
    ...:         for term in sent.split():
    ...:             if hunt in term:
    ...:                 yield term
    ...:                 

In [34]: list(hunter(sent_list))
Out[34]: ['youth', 'youthful']

只是为了证明您也可以使用term.find(hunt),因为您已经在使用它:

In [35]: def hunter(sent_list):
    ...:     for sent in sent_list:
    ...:         for term in sent.split():
    ...:             if term.find(hunt) is not -1:
    ...:                 yield term
    ...:                 

In [36]: list(hunter(sent_list))
Out[36]: ['youth', 'youthful']

【讨论】:

    【解决方案2】:

    更简单的方法是将.split 将每个句子放入单个句子的列表中。从那里你可以遍历每一个,拆分它,然后检查单词是否在句子中。

    hunt = "youth"
    def hunter(sent):
        sentences = sent.split('.')
        for each in sentences:
            check = each.split(' ')
            for word in check:
                if word = hunt:
                    print each
    

    【讨论】:

      猜你喜欢
      • 2020-06-17
      • 2014-09-19
      • 2023-01-24
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多