【问题标题】:determining context from text using pandas使用 pandas 从文本中确定上下文
【发布时间】:2016-11-30 09:22:39
【问题描述】:

我已经构建了一个网络爬虫来获取我的数据。数据通常是结构化的。但随后又出现了一些异常情况。现在要对数据进行分析,我正在搜索几个单词,即searched_words=['word1','word2','word3'......] 我想要这些单词所在的句子。所以我编码如下:

searched_words=['word1','word2','word3'......]

fsa = re.compile('|'.join(re.escape(w.lower()) for w in searched_words))
str_df['context'] = str_df['text'].apply(lambda text: [sent for sent in     sent_tokenize(text)
if any(True for w in word_tokenize(sent) if w.lower() in words)])

它正在工作,但我面临的问题是,如果文本中的句号后缺少空格,我会得到所有这样的句子。

例子:

searched_words = ['snakes','venomous']
text = "I am afraid of snakes.I hate them."
output : ['I am afraid of snakes.I hate them.']
Desired output : ['I am afraid of snakes.']

【问题讨论】:

  • 您能否展示或分享您正在处理的数据样本?
  • @RohanAmrute 这与我在问题中说明的示例相似。
  • tokenize() 中发生了什么?你能代替'。'和 '。 '?点和空格
  • @themistoklik 我尝试过同样的方法,但徒劳无功!如果出现缩写,我会丢失数据。
  • 在输出阶段发生替换,仍然丢失数据?

标签: python pandas nltk text-analysis


【解决方案1】:

如果所有标记器(包括 nltk)都失败了,你可以自己动手尝试

import re
s='I am afraid of snakes.I hate venomous them. Theyre venomous.'
def findall(s,p):
  return [m.start() for m in re.finditer(p, s)]

def find(sent, word):
  res=[]
  indexes = findall(sent,word)

  for index in indexes:
    i = index
    while i>0:
      if sent[i]!='.':
        i-=1
      else:
        break
    end = index+len(word)

    nextFullStop = end + sent[end:].find('.')

    res.append(sent[i:nextFullStop])
    i=0
  return res

玩它here。里面还有一些点,因为我不知道你想对它们做什么。

它的作用是找到所说单词的所有出现,并让您将句子一直返回到前一个点。这仅适用于边缘情况,但您可以根据自己的需要轻松调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多