【问题标题】:Python: Create a new variable derived from extracting a sentence from a textPython:创建一个从文本中提取句子派生的新变量
【发布时间】:2018-08-01 18:53:41
【问题描述】:

我有一个数据框,其中一个变量是包含许多句子的相当长的段落。有时句子用句号分隔,有时用逗号分隔。我试图通过使用选定的单词仅提取文本的选定部分来创建一个新变量。请在下面查看我目前获得的结果的数据框的简短示例,然后是我正在使用的代码。注意 - 第一个变量中的文本非常大。

PhysicalMentalDemands           Physical_driving       Physical_telephones

[driving may be necessary       [driving......]        [telephones...]
occasionally. 
as well as telephones will also 
be occasional to frequent.]  

使用的代码:

searched_words = ['driving' , 'telephones']

for i in searched_words:
  Test ['Physical' +"_"+  str(i)] = Test ['PhysicalMentalDemands'].apply(lambda text: [sent for sent in sent_tokenize(text)
                       if any(True for w in word_tokenize(sent) 
                                 if w.lower() in searched_words)])

问题:

目前我的代码提取句子但同时使用这两个词进行提取。我似乎有其他类似的帖子,但没有一个能够解决我的问题。

已修复

searched_words = ['驾驶','身体']

for i in searched_words:
df['Physical' + '_' + i] = result['PhysicalMentalDemands'].str.lower().apply(lambda text: [sent for sent in sent_tokenize(text) 
                                                           if i in word_tokenize(sent)])

【问题讨论】:

  • 在“问题”部分,您说“使用这两个词提取”,这是否意味着它仅在两个词都存在时才匹配?如果其中一个存在,您是否尝试匹配?
  • @Henry Woody ,正在发生的事情是两个句子都指向两个变量。我的功能不是将一个变量中的驾驶和另一个变量中的电话分开。

标签: python nlp


【解决方案1】:

如果您想为每个搜索的单词提供单独的列表,您可以考虑将您的代码重新组织成如下内容:

searched_words = ['driving', 'telephones']

for searched_word in searched_words:
    Test ['Physical' +"_"+  searched_word)] = Test ['PhysicalMentalDemands'].apply(lambda text: [sent for sent in sent_tokenize(text)
                if any(w for w in word_tokenize(sent) if w.lower() == searched_word)])

请注意,修复的重点是将 if w.lower() in searched_words 更改为 if w.lower() == searched_word

【讨论】:

  • 它不起作用,它返回空白。我可能在考虑之前的任何()
  • @Ian_De_Oliveira 我注意到一个小问题,我在那里留下了对i 的引用,但听起来这不是你的问题。我刚刚在我的电脑上运行了它,它似乎工作正常。我能想到的唯一可能导致该问题的是将searched_words 放在searched_word 应该去的地方。
  • 我还在搜索词中使用 for i 实现了您的答案,然后 ==i 并且效果很好。等号很简洁,我肯定会使用。 tks
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多