【问题标题】:How do I singularize and lemmatize an entire pandas dataframe column using TextBlob?如何使用 TextBlob 对整个 pandas 数据框列进行单数化和词形还原?
【发布时间】:2019-12-15 10:15:59
【问题描述】:

我有一个 pandas 数据框,其中包含以下列:df['adjectives']、df['nouns'] 和 df['adverbs']。这些列中的每一列都包含基于其各自词性的标记列表。

我想使用 TextBlob 在我的数据框中创建三个新列,df['adjlemmatized']、df['nounlemmatized'] 和 df['advlemmatized']。

这些列中的每一列都应包含由单数化引理形式的单词组成的单词列表。

我已尝试遵循 TextBlob 文档,但我一直在编写将迭代整个数据帧的函数。

Words Inflection and Lemmatization

Each word in TextBlob.words or Sentence.words is a Word object (a subclass of unicode) with useful methods, e.g. for word inflection.

>>> sentence = TextBlob('Use 4 spaces per indentation level.')
>>> sentence.words
WordList(['Use', '4', 'spaces', 'per', 'indentation', 'level'])
>>> sentence.words[2].singularize()
'space'
>>> sentence.words[-1].pluralize()
'levels'
Words can be lemmatized by calling the lemmatize method.

>>> from textblob import Word
>>> w = Word("octopi")
>>> w.lemmatize()
'octopus'
>>> w = Word("went")
>>> w.lemmatize("v")  # Pass in WordNet part of speech (verb)
'go'

这是我用来从文本中获取词性的代码:

# get adjectives
def get_adjectives(text):
    blob = TextBlob(text)
    print(text)
    return [word for (word,tag) in blob.tags if tag.startswith("JJ")]
df['adjectives'] = df['clean_reviews'].apply(get_adjectives)

【问题讨论】:

  • 您的数据框目前有哪些列?一个形容词,一个名词,一个副词?
  • 是的,但我也有一个包含派生词性词表的文本本身。

标签: python pandas text data-cleaning lemmatization


【解决方案1】:

如果您的文字已经被标记化并且您希望保持这种方式,这很容易:

df['adjlemmatized'] = df.adjectives.apply(lambda x: [ TextBlob(w) for w in x])
df['adjlemmatized'] = df.adjlemmatized.apply(lambda x: [ w.lemmatize() for w in x])

【讨论】:

  • 这两个都抛出错误:“AttributeError: 'str' object has no attribute 'lemmatize'”
  • 对不起,忘记添加TextBlob,现在我已经编辑了。如果这不起作用,请照常在本网站上发布您的数据样本
  • 现在收到语法错误。请参阅链接以获取我的数据示例。 filedropper.com/sample_2
  • 我把它分成两个步骤,但我认为错误是因为一个额外的括号。我这里没有安装Textblob,所以我无法测试我的代码。现在可以用了吗?
  • 感谢您的帮助。不幸的是我仍然遇到这个错误:“AttributeError:'str'对象没有属性'lemmatize'”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
相关资源
最近更新 更多